System.out.println("Modified sequence: " + str);
}
}
The output is shown here:
Original sequence: Jon Jonathan Frank Ken Todd
Modified sequence: Eric Eric Frank Ken Todd
Because the regular expression βJon.*? β matches any string that begins with Jon followed
by zero or more characters, ending in a space, it can be used to match and replace both Jon
and Jonathan with the name Eric. Such a substitution is not possible without pattern matching
capabilities.
Using split( )
You can reduce an input sequence into its individual tokens by using thesplit( )method
defined byPattern. One form of thesplit( )method is shown here:
String[ ] split(CharSequencestr)
It processes the input sequence passed instr,reducing it into tokens based on the delimiters
specified by the pattern.
For example, the following program finds tokens that are separated by spaces, commas,
periods, and exclamation points:
// Use split().
import java.util.regex.*;
class RegExpr9 {
public static void main(String args[]) {
// Match lowercase words.
Pattern pat = Pattern.compile("[ ,.!]");
String strs[] = pat.split("one two,alpha9 12!done.");
for(int i=0; i < strs.length; i++)
System.out.println("Next token: " + strs[i]);
}
}
The output is shown here:
Next token: one
Next token: two
Next token: alpha9
Next token: 12
Next token: done
As the output shows, the input sequence is reduced to its individual tokens. Notice that the
delimiters are not included.
832 Part II: The Java Library