Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 27: NIO, Regular Expressions, and Other Packages 831


As the output shows, the pattern “e.+?d” will match the shortest sequence that begins with
eand ends withd. Thus, two matches are found.


Working with Classes of Characters
Sometimes you will want to match any sequence that contains one or more characters, in
any order, that are part of a set of characters. For example, to match whole words, you want
to match any sequence of the letters of the alphabet. One of the easiest ways to do this is to
use a character class, which defines a set of characters. Recall that a character class is created
by putting the characters you want to match between brackets. For example, to match the
lowercase characters a through z, use[a-z]. The following program demonstrates this technique:


// Use a character class.
import java.util.regex.*;


class RegExpr7 {
public static void main(String args[]) {
// Match lowercase words.
Pattern pat = Pattern.compile("[a-z]+");
Matcher mat = pat.matcher("this is a test.");


while(mat.find())
System.out.println("Match: " + mat.group());
}
}


The output is shown here:


Match: this
Match: is
Match: a
Match: test

Using replaceAll( )
ThereplaceAll( )method supplied byMatcherlets you perform powerful search and replace
operations that use regular expressions. For example, the following program replaces all
occurrences ofsequences that begin with “Jon” with “Eric”:


// Use replaceAll().
import java.util.regex.*;


class RegExpr8 {
public static void main(String args[]) {
String str = "Jon Jonathan Frank Ken Todd";


Pattern pat = Pattern.compile("Jon.*? ");
Matcher mat = pat.matcher(str);

System.out.println("Original sequence: " + str);

str = mat.replaceAll("Eric ");
Free download pdf