View RSS Feed

My Java Tips

Matching Patters using Regex

Rate this Entry
by , 11-10-2011 at 06:18 PM (1021 Views)
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:


* is used to denote any number of occurrences.

Consider following example:

Java Code:
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);

			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.



Submit "Matching Patters using Regex" to Facebook Submit "Matching Patters using Regex" to Digg Submit "Matching Patters using Regex" to Submit "Matching Patters using Regex" to StumbleUpon Submit "Matching Patters using Regex" to Google

Java SE