Datasheet
Method Description
String replaceAll(String Replaces all occurrences of the string that match the pattern
replacement) with the string replacement. The Matcher should be reset if it
will still be used after this method is called.
String replaceFirst(String Replaces only the first string that matches the pattern with the
replacement) string replacement. The Matcher should be reset if it will still
be used after this method is called.
The MatchResult Interface
The MatchResult interface contains the group methods, and start and end methods, to provide a
complete set of methods allowing for describing the current state of the
Matcher. The Matcher class
implements this interface and defines all these methods. The
toMatchResult method returns a handle
to a
MatchResult, which provides for saving and handling the current state of the Matcher class.
Regular Expression Example
Use the Pattern/Matcher classes to process a Java source code file. All classes that aren’t public will be
listed (all classes that have no modifiers, actually), and also all doubled words (such as two identifiers in
a row) are listed utilizing back references.
The input source code file (which does not compile) is shown as follows:
import java.util.*;
class EmptyClass {
}
class MyArrayList extends extends ArrayList {
}
public class RETestSource {
public static void main(String args[]) {
System.out.println(“Sample RE test test source code code”);
}
}
The program utilizing regular expressions to process this source code follows:
import java.util.*;
import java.util.regex.*;
import java.io.*;
public class RegExpExample {
public static void main(String args[])
{
String fileName = “RETestSource.java”;
String unadornedClassRE = “^\\s*class (\\w+)”;
68
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 68