www.developer.com/lang/other/article.php/908271
|
October 22, 2001 Regular expressions have been around for a long time. They come in very handy for text processing tasks. Some attribute the success of Perl to its superb ability of handling regular expressions. While there have been third-party classes that support regular expressions, with JDK 1.4, Java provides native support via the java.util.regex package.
Usage of regular expressions boils down to two components:
The Pattern class focuses on the first component. You use this class to define a regular expression. By representing the regular expression as an object, you can reuse the expression in your code. This is particularly useful in cases where you need to apply the same expression to multiple strings (e.g., line-by-line processing of a text file). The following line creates a pattern based on the regular expression
Pattern p = Pattern.compile("[0-9]");
The documentation for the Pattern class provides a useful summary of regular expression constructs. It also provides a comparison to Perl 5 regular expressions. The Pattern class includes several fields that allow you to control its behavior. They include CANON_EQ, CASE_SENSITIVE, DOTALL, MULTILINE, and UNICODE_CASE. You can pass these flags to the Once you have the pattern defined, you will use the Matcher class to apply that pattern to a character sequence (usually a String). The following two lines demonstrate this:
Matcher m = p.matcher("abcd55efg");
boolean matchFound = m.matches();
Listing 1 is a simple class that searches for a pattern consisting of characters followed by two digits, followed by more characters. The pattern is applied to the string Listing 1.
import java.util.regex.*;
class regexSample {
public static void main(String args[]) {
Pattern p = Pattern.compile("[a-z]*[0-9][0-9][a-z]*");
Matcher m = p.matcher("abcd55efg");
boolean matchFound = m.matches();
if (matchFound)
System.out.println("Match was found.");
else
System.out.println("No match.");
}
}
Aside from a "match" operation, the Matcher class provides a number of other methods. Once a match is found, the Listing 2.
class regexSample2 {
public static void main(String args[]) {
Pattern p = Pattern.compile("[0-9][0-9]");
Matcher m = p.matcher("abcd55efg");
boolean matchFound = m.find();
if (matchFound)
System.out.println("Match was found.");
else
System.out.println("No match.");
}
}
We will get a match because the pattern of two successive digits is within the input source (i.e., The Regular expressions are a useful programming tool. The fact that Java now natively supports them simplifies many programming tasks that used to require cumbersome code dealing with character arrays and StringTokenizer. About the AuthorPiroz Mohseni is a principle with Bita Technologies, focusing on business improvement through the effective use of technology. His areas of interest include enterprise Java, XML, and e-commerce applications. |