A Java regular expression example (featuring Pattern and Matcher classes)

Summary: Java regular expressions in Java 1.4, featuring regex expressions and pattern matching, using the new Java Pattern and Matcher classes.

The following Java example offers an introduction to regular expressions in Java 1.4. In this code we're creating a regular expression that can search for a date. Specifically, that date must be in a format of two digits, followed by a hyphen, followed by two digits, followed by a hyphen, followed by four digits.

This date pattern is created in this line of code:

Pattern datePattern = Pattern.compile("date: (\\d{2})-(\\d{2})-(\\d{4})");

Beyond that, this pattern example also shows how to use parentheses to create groups that you can use later. Notice that the three portions of the date (month, day, and year) are enclosed in parentheses. This creates three groups, and the three groups are referred to later in the code after that dateMatcher.find() statement. 

Yikes, so much more could be said about Java pattern matching, so if you want to know more just add a comment below, and I'll put more out here.

Without any further ado, here is our example Java DateMatcher.java class:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateMatcher
{
  public DateMatcher()
  {
    String aDate = "date: 12-15-2003";
    Pattern datePattern = Pattern.compile("date: (\\d{2})-(\\d{2})-(\\d{4})");
    Matcher dateMatcher = datePattern.matcher(aDate);
    if (dateMatcher.find())
    {
      System.out.println("Month is: " + dateMatcher.group(1));
      System.out.println("Day is:   " + dateMatcher.group(2));
      System.out.println("Year is:  " + dateMatcher.group(3));
    }
  }

  public static void main(String[] args)
  {
    new DateMatcher();
  }
}

One other thing: original credits go to Darren Day for creating this example Java pattern matching class for a "New Features of Java 1.4" seminar that we put together a few years ago.