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:

  1. Creates a Pattern p using the String "[a-z]+".
  2. Creates a Matcher m to apply Pattern p to the text "Now is the time".
  3. Repeatedly finds substrings of the text that match the pattern (using 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.