Matching Patters using Regex

1 November 2007

Java developers who are working on text parser or text extractor in Java face problems while search a specific pattern in the text. Searching patterns is not an easy task using standard java string operations. Fortunately we can use regular expressions in java which makes pattern matching easier and simply. Java.util.regex is the package which comes to our rescue.

One should have a little knowledge of regular expressions to make use of regex. For instance [] is used to give range of allowed characters and {} is used to give no of characters. Lets take an example:

“Test[a-z]{2}String” means that there should be 2 letters between Test and String and those letters can be any letter between a to z. Remember Java is case sensitive. So if you want to a regular expression that can have 2 characters upper or lower case between Test and String, then following regular expression is valid:

“Test[a-zA-Z]{2}String”

* is used to denote any number of occurrences.

Consider following example:

import java.util.regex.*;
...
String patternStr = "Test[a-zA-Z]{2}String";
Pattern pattern = Pattern.compile(patternStr);
CharSequence inputStr =  "testing TestKkString Testktring TestkkkString TestbhString.";
Matcher matcher = pattern.matcher(inputStr);
 
while(matcher.find())
	{
			int start = matcher.start();
			int end = matcher.end();
			System.out.println(inputStr.subSequence(start, end));
	}

Variable patternStr contains the regular expression that is to be searched and inputStr contains the string in which we have to look for the required expression. We are searching for the pattern “Test[a-zA-Z]{2}String” which means there should be exactly 2 character from A to Z or from a to z between Test and String. We will iterate though all the occurrences of findings through method find() of Matcher class and will print the matched text on the console.

Output:

TestKkString
TestbhString

del.icio.us:Matching Patters using Regex  digg:Matching Patters using Regex  spurl:Matching Patters using Regex  wists:Matching Patters using Regex  simpy:Matching Patters using Regex  newsvine:Matching Patters using Regex  blinklist:Matching Patters using Regex  furl:Matching Patters using Regex  reddit:Matching Patters using Regex  fark:Matching Patters using Regex  blogmarks:Matching Patters using Regex  Y!:Matching Patters using Regex  smarking:Matching Patters using Regex  magnolia:Matching Patters using Regex  segnalo:Matching Patters using Regex  gifttagging:Matching Patters using Regex

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Matching Patters using Regex

Leave a Reply