September 23, 2004

New regular expression feature of Java 5.0

The java.util.regex package has been enhanced in Java 5.0. One nice new feature is the ability to save the results of a find() operation into a MatchResult object. Prior to Java 5.0, you could query a Matcher for the results of the most recent find() , but the results would be overwritten by the next find().

The new MatchResult interface lends itself to code like the following:

import java.util.regex.*;
import java.util.*;

public class FindAll {
    public static void main(String[] args) {
	Pattern pattern = Pattern.compile(args[0]);
	String text = args[1];

	List<MatchResult> results = findAll(pattern, text);
	for(MatchResult r : results) {
	    System.out.printf("Found '%s' at (%d,%d)%n",
			      r.group(), r.start(), r.end());
	}
    }

    public static List<MatchResult> findAll(Pattern pattern, CharSequence text)
    {
	List<MatchResult> results = new ArrayList<MatchResult>();
	Matcher m = pattern.matcher(text);
	while(m.find()) results.add(m.toMatchResult());
	return results;
    }
}

This code also demonstrates generics, the for/in loop, and the printf() method, all of which are also new in Java 5.0 | TrackBack