Java Reference
In-Depth Information
1
// Fig. 14.24: RegexMatches.java
2
// Classes Pattern and Matcher.
3
import java.util.regex.Matcher;
4
import java.util.regex.Pattern;
5
6
public class RegexMatches
7
{
8
public static void main(String[] args)
9
{
10
// create regular expression
11
Pattern expression =
Pattern.compile( "J.*\\d[0-35-9]-\\d\\d-\\d\\d" );
12
13
14
String string1 = "Jane's Birthday is 05-12-75\n" +
15
"Dave's Birthday is 11-04-68\n" +
16
"John's Birthday is 04-28-73\n" +
17
"Joe's Birthday is 12-17-77" ;
18
19
// match regular expression to string and print matches
20
Matcher matcher = expression.matcher(string1);
21
22
while (matcher.find())
System.out.println(matcher.group());
23
24
}
25
} // end class RegexMatches
Jane's Birthday is 05-12-75
Joe's Birthday is 12-17-77
Fig. 14.24 | Classes Pattern and Matcher .
Lines 11-12 create a Pattern by invoking static Pattern method compile . The dot
character " . " in the regular expression (line 12) matches any single character except a new-
line character. Line 20 creates the Matcher object for the compiled regular expression and
the matching sequence ( string1 ). Lines 22-23 use a while loop to iterate through the
String . Line 22 uses Matcher method find to attempt to match a piece of the search
object to the search pattern. Each call to this method starts at the point where the last call
ended, so multiple matches can be found. Matcher method lookingAt performs the same
way, except that it always starts from the beginning of the search object and will always
find the first match if there is one.
Common Programming Error 14.3
Method matches (from class String , Pattern or Matcher ) will return true only if the en-
tire search object matches the regular expression. Methods find and lookingAt (from class
Matcher ) will return true if a portion of the search object matches the regular expression.
Line 23 uses Matcher method group , which returns the String from the search object
that matches the search pattern. The String that's returned is the one that was last
matched by a call to find or lookingAt . The output in Fig. 14.24 shows the two matches
that were found in string1 .
 
Search WWH ::




Custom Search