2010-10-11

Groovy regular expression operators

The Java regular expression (regex) typical invocation sequence is:

     Pattern p = Pattern.compile("a*b");
     Matcher m = p.matcher("aaaaab");
     boolean b = m.matches();

A matches method is defined by the Pattern class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement

    boolean b = Pattern.matches("a*b", "aaaaab");

Groovy is a promising new language for the Java platform that includes the following regular expressions operators that greatly simplify the use of java.util.regex:

~ creates a Pattern from String

=~ creates a Matcher, and in a boolean context, it is "true" if it has at least one match, "false" otherwise.

==~ tests if String matches the pattern

No comments: