| CIT 597 Example: Regular Expressions Fall 2002, David Matuszek |
Here is a trivial example of using regular expressions in Java 1.4. This program does the following:
p using the String "[a-z]+".m to apply Pattern p to the
text "Now is the time".m.find()),
extracts them from the text (using text.substring(m.start(), m.end())),and
prints them on one line, following each by an asterisk.
import java.util.regex.*;
public class RegexTest {
public static void main(String args[]) {
String pattern = "[a-z]+";
String text = "Now is the time";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.print(text.substring(m.start(), m.end()) + "*");
}
}
}
|
The resultant output is: ow*is*the*time*
Note that the pattern p can be used again, but m
is "used up"--a new Matcher must be assigned to m before
it can be used again.