This tutorial presents Java powerful regular-expression processing capabilities using class
Matcher and class
matches method. This tutorial is intended for students and developers who are familiar with basic Java string-processing techniques.
[Note: This tutorial is an excerpt (Section 29.7) of Chapter 29, Strings, Characters and Regular Expressions, from our textbook Java How to Program, 6/e. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp.1378-1387. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]29.7 Regular Expressions, Class Pattern and Class Matcher (Continued)
Figure 29.24 presents a simple example that employs regular expressions. This program matches birthdays against a regular expression. The expression only matches birthdays that do not occur in April and that belong to people whose names begin with "J".
|Fig. 29.24||Regular expressions checking birthdays.|
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 newline 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 29.5
|Method matches (from class String, Pattern or Matcher) will return true only if the entire 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 is returned is the one that was last matched by a call to find or lookingAt. The output in Fig. 29.24 shows the two matches that were found in string1.
Regular Expression Web Resources
This section presents several of Java’s regular-expression capabilities. The following Web sites provide more information on regular expressions.
Thoroughly describes Java’s regular-expression capabilities.
This tutorial explains how to use Java’s regular-expression API.
This page is the javadoc overview of package java.util.regex.