832
Part II:
The Java Library
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 the split( ) method
defined by Pattern. One form of the split( ) method is shown here:
String[ ] split(CharSequence str)
It processes the input sequence passed in str, 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.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home