Saturday, June 9, 2007

Regular Expression- Pattern Matching in java

Java provides a package called 'java.util.regex' for pattern matching.

The java.util.regex package has two classes and one exception class, the two classes namely - Pattern and Matcher.

A small example code given below validates the string with the given regular expression.

 import java.util.regex.Matcher;  
import java.util.regex.Pattern;

public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\d*"); //reg exp for 0 or more integers
Matcher matcher = null;
matcher = pattern.matcher("1111");

if (matcher.matches()) {
System.out.println("Matched");
} else {
System.out.println("Not Matched");
}
}
}

Similarly, there are more regular expression format and quantifiers.

No comments: