Thursday, January 10, 2008

Regular expression in java

String input = "something";

1. write a regular expression
String regex="your_reg_ex"; 

2. create a pattern object compiling your regex

Pattern p = Pattern.compile(regex);

3. create a matcher object that will match input string with the compiled regex

Matcher m = p.matcher(input);

4. check whether any matching found

if (m.find())
//5. if found, the matched portion will be available at
String found =;
// do whatever u like

let, input = "fjkl;pokjhA123ss456Apghkit"
u want to read block between 2 A's
regex = (?<=X).*?(?=X) where X = "A" here output = "123ss456" u can only use fixed length string in (?<=X), never use .*? or + in X otherwise u'll get exception
Look-behind group does not have an obvious maximum length near index ..

Java code for this:
 2   String regularExp = "(?<=A).*?(?=A)";

 4   String input = "fjkl;pokjhA123ss456Apghkit";

 6   Pattern pattern = Pattern.compile(regularExp);

 8   Matcher matcher =  pattern.matcher(input);

10      if(matcher.find())
11         {

12         String parsedData =;
13                 System.out.println(" Output ->"+parsedData);

14          }


Arshad said...

Can u give the java code corresponding to your example? thanks!

sheetal said...

I've updated it sir. sorry for late :)

Arshad said...

Thanks :D

Wolf said...

Regular expression is really wonderful to parsing HTML or matching pattern. I use this a lot when i code. Actually when I learn any new langauge, first of all I first try whether it supports regex or not. I feel ezee when I found that.

Here is about ruby regex. This was posted by me when I first learn ruby regex. So it will be helpfull for New coders.