Thursday, January 10, 2008

Regular expression in java

http://java.sun.com/developer/technicalArticles/releases/1.4regex/

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 m.group()
String found = m.group();
// 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:
 1 
 2   String regularExp = "(?<=A).*?(?=A)";

 3 
 4   String input = "fjkl;pokjhA123ss456Apghkit";
 5 

 6   Pattern pattern = Pattern.compile(regularExp);

 7   
 8   Matcher matcher =  pattern.matcher(input);

 9      
10      if(matcher.find())
11         {

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

14          }
15        

3 comments:

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