Saturday, 1 November 2014

Exploring Pattern class

Pattern object represents a compiled representation of a regular expression.

Methods in Pattern class
Method
Description
public static Pattern compile(String regex)
Compiles the given regular expression into a pattern.
public static Pattern compile(String regex, int flags)
Compiles the given regular expression into a pattern with the given flags.
public String pattern()
Returns the regular expression from which this pattern was compiled.
public String toString()
Returns the string representation of this pattern.
public Matcher matcher(CharSequence input)
Creates a matcher that will match the given input against this pattern.
public int flags()
Returns this pattern's match flags.
public static boolean matches(String regex, CharSequence input)
Compiles the given regular expression and attempts to match the given input against it.
public String[] split(CharSequence input, int limit)
Splits the given input sequence around matches of this pattern.





Prevoius                                                 Next                                                 Home

regular expression to validate java variable name

A variable's name can be any legal identifier, an unlimited-length sequence of letters and digits, $, _ and beginning with a letter, the dollar sign "$", or the underscore character "_".

1. A variable name must begin with a letter or $ or _.
[a-zA-Z$_]

2. After first character any letter, digit, $ or _ is valid.
[a-zA-Z0-9$_]*

Now the final regular expression is [a-zA-Z$_][a-zA-Z0-9$_]*
import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);
                System.out.println(matcher.matches());               
            }
            catch(Exception e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output

Enter Regular Expression
[a-zA-Z$_][a-zA-Z0-9$_]*
Enter the string
abc
true
Enter the string
_123
true
Enter the string
abc$_123
true
Enter the string
123
false
Enter the string
12abc
false



Prevoius                                                 Next                                                 Home

Escape sequence

Escape sequence is useful to match a character that is a metacharacter.

For Example, if you want to check IP address. If you specify a regular expression like below.
\d{3}.\d{3}.\d{3}.\d{3}

Sample Output
Enter Regular Expression
\d{3}.\d{3}.\d{3}.\d{3}
Enter the string
123.456.789.012
I found the text 123.456.789.012 starting at index 0 Ending at index 15

Enter the string
1234567890987654
I found the text 123456789098765 starting at index 0 Ending at index 15

As you observe the above output, in addition to matching the IP addresses, given regular expression also match '1234567890987654', since '.' can match any character.

Now update the regular expression using escape sequence '\' like below.

\d{3}\.\d{3}\.\d{3}\.\d{3}

Sample Output
Enter Regular Expression
\d{3}\.\d{3}\.\d{3}\.\d{3}
Enter the string
123.456.789.091
I found the text 123.456.789.091 starting at index 0 Ending at index 15

Enter the string
1234567890987654





Prevoius                                                 Next                                                 Home

Word boundary

Usually a regular expression match the word, even that is embedded in other word.

For Example
Enter Regular Expression
repeat
Enter the string
Don't repeat the repeated things
I found the text repeat starting at index 6 Ending at index 12
I found the text repeat starting at index 17 Ending at index 23

In the string 'Don't repeat the repeated things', regular expression matches the word twice, first one from the word 'repeat' and second one from the word 'repeated'.

By using '\b' you can specify the boundary for the word.

Enter Regular Expression
repeat\b
Enter the string
Don't repeat the repeated things
I found the text repeat starting at index 6 Ending at index 12

But the same regular expression match the word 'repeat' in the string 'prepeat'.

Enter the string
prepeat
I found the text repeat starting at index 1 Ending at index 7

So to exactly match the word 'repeat' use the regular expression '\brepeat\b'.

Enter Regular Expression
\brepeat\b
Enter the string
Don't repeat the repeated things
I found the text repeat starting at index 6 Ending at index 12

Enter the string
prepeat

Enter the string
repeat repeated
I found the text repeat starting at index 0 Ending at index 6





Prevoius                                                 Next                                                 Home

Start(^) and End($) of the Line

Carret (^) and dollar($) represents start and end of a line respectively.

Regular expression '^cat' matches any line, that starts with string 'cat'.

Sample runs of Harness program.

Enter Regular Expression
^cat
Enter the string
cat
I found the text cat starting at index 0 Ending at index 3

Enter the string
cat is a cat
I found the text cat starting at index 0 Ending at index 3

Enter the string
cat is animal
I found the text cat starting at index 0 Ending at index 3

Enter the string
cattering
I found the text cat starting at index 0 Ending at index 3

Enter the string
mcat
java.lang.IllegalStateException: No match found




Prevoius                                                 Next                                                 Home

Boundary Matchers


Boundary Construct
Description
^
The beginning of a line
$
The end of a line
\b
A word boundary
\B
A non-word boundary
\A
The beginning of the input
\G
The end of the previous match
\Z
The end of the input but for the final terminator, if any
\z
The end of the input




Prevoius                                                 Next                                                 Home

Backreferences

Capturing groups can remember text matched by the expression they enclose. Backreferencing is a feature that use the remembering capacity of Capturing groups.

Capturing Group
Description
\n
Matches with whatever the nth capturing group matched.
\k<name>
Matches with whatever the named-capturing group "name"matched.

For Example, regular expression '(\d{4}) \1' match the 4 digits which are repeating twice.

Enter Regular Expression
(\d{4}) \1
Enter the string
1234 1234
I found the text 1234 1234 starting at index 0 Ending at index 9

Enter the string
1234 5678 5678 1234
I found the text 5678 5678 starting at index 5 Ending at index 14

Another Example, regular expression '([a-z,A-Z]*) \1' match if same striing repeated twice.

Enter Regular Expression
([a-z,A-Z]*) \1
Enter the string
hari hari
I found the text hari hari starting at index 0 Ending at index 9

Enter the string
krishna krishna
I found the text krishna krishna starting at index 0 Ending at index 15

Enter the string
my name name is krishna
I found the text starting at index 2 Ending at index 3
I found the text name name starting at index 3 Ending at index 12
I found the text starting at index 12 Ending at index 13
I found the text starting at index 15 Ending at index 16


Enter Regular Expression
(a((b){2})) \2
Enter the string
abb bb
I found the text abb bb starting at index 0 Ending at index 6

Example 1 : Backreferencing using naming
import java.util.regex.*;
        
public class CaptureGroupEx {
    public static void main(String args[]){
        String name = "(?<number>\\d+)\\s\\k<number>";
        Matcher m = Pattern.compile(name).matcher("1234 1234");
        
        while (m.find()) {
            System.out.print("I found the text " + m.group());
            System.out.print(" starting at index " + m.start());
            System.out.println(" Ending at index " + m.end());
        }        
    }
}

Output

I found the text 1234 1234 starting at index 0 Ending at index 9




Prevoius                                                 Next                                                 Home