Friday, 31 October 2014

Regular expression

This article talks about the classes and quantifiers allowing to execute design pattern on a String.


The classes "Pattern" and "Matcher"


A search in a string with the regular expression's language can be used with the classes "Pattern" and "Matcher".

Eg.
String aSource = "You can search in this example of search string.";
String aPattern = "search|example";

// We create a "Pattern" object with the pattern string
Pattern pattern = Pattern.compile(aPattern);

// The Matcher object contains the source's values which match with the pattern
Matcher matcher = pattern.matcher(aSource);

System.out.println("Matches:");

while(matcher.find()){
   System.out.println("- a match '"+matcher.group()+"' found between characters "+matcher.start()+" and "+matcher.end());
}

Output:
Matches:
- a match 'search' found between characters 8 and 14
- a match 'example' found between characters 23 and 30
- a match 'search' found between characters 34 and 40


Greedy and reluctant quantifiers


Greedy: read the entire source first, and then read backward from the end to the beginning of the source (from right to left).

Reluctant: read from the left to the right and consumes character by character.

Quantifiers:
? is greedy, ?? is reluctant
* is greedy, *? is reluctant
+ is greedy, +? is reluctant

Eg.
source = "yyxxxyxx";
pattern = ".*xx"; // greedy quantifier
 // regex instructions...

Result:
yyxxxyxxx


Eg.
source = "yyxxxyxx";

// reluctant quantifier
pattern = ".*?xx";

// regex instructions...

Result:
yyxx
xyxx

For more info see Sun's API:
http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html


Meta characters


Meta-character
Description
.
Any character
\d
A digit [0-9]
\D
A non digit [^0-9]
\s
A white space character
\S
A non white space character
\w
A word character (letters, digits or _ ) [a-zA-z_0-9]
\W
A non word character [^\w]

When you use them in a string pattern, add an additional backslash before the first backslash as follows:
String aPattern = "\\d";

If you use only one backslash, the compiler will look for an escape character (like '\n', '\b', '\t', ...).
The following code will not compile:
String aPattern = "\d";

Compilation error:
illegal escape character


The class "Scanner"


You can also use regular expression with the class "Scanner" as follows:
String aSource = "1b2c335f456";
String aPattern = "\\d\\d";
String token = "";

Scanner scanner = new Scanner(aSource);

while ( (token = scanner.findInLine(aPattern)) != null) {
System.out.println("- token: "+token);
}

Output:
- token: 33
- token: 45