Datasheet
Several examples of using regular expressions are examined throughout this section. As an initial exam-
ple, assume you want to generate a list of all classes inside Java files that have no modifier before the
keyword
class. Assuming you only need to examine a single line of source code, all you have to do is
ignore any white space before the string
class, and you can generate the list.
A traditional approach would need to find the first occurrence of
class in a string and then ensure
there’s nothing but white space before it. Using regular expressions, this task becomes much easier. The
entire Java regular expression language is examined shortly, but the regular expression needed for this
case is
\s*class. The backslash is used to specify a meta-character, and in this case, \s matches any
white space. The asterisk is another meta-character, standing for “0 or more occurrences of the previous
term.” The word
class is then taken literally, so the pattern stands for matching white space (if any
exists) and then matching
class. The Java code to use this pattern is shown next:
Pattern pattern = Pattern.compile(“\\s*class”);
// Need two backslashes to preserve the backslash
Matcher matcher = pattern.matcher(“\t\t class”);
if(matcher.matches()) {
System.out.println(“The pattern matches the string”);
} else {
System.out.println(“The pattern does not match the string”);
}
This example takes a regular expression (stored in a Pattern object) and uses a matcher to see if the reg-
ular expression matches a specific string. This is the simplest use of the regular expression routines in
Java. Consult Figure 1-2 for an overview of how the regular expression classes work with each other.
Figure 1-2
Pattern
OBJECT
Input string
Regular
Expression
(string)
Used by
The Pattern object
contains the compiled
version of the regular
expression and can be
reused
The Matcher object is
responsible for testing a
compiled Pattern against
a string and possibly
performing other tasks
Matcher
OBJECT
Get matched text
Matched text
Is there a match?
Yes/No
61
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 61