Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »

Groovy supports regular expressions natively using the ~"..." expression, which compiles a Java Pattern object from the given string. Groovy also supports the =~ (create Matcher) and ==~ (matches regex) operators.

Error rendering macro 'code': Invalid value specified for parameter 'lang'
import java.util.regex.Matcher
import java.util.regex.Pattern

assert "cheesecheese" =\~ "cheese"
assert "cheesecheese" =\~ /cheese/
assert "cheese" == /cheese/   /*they are both string syntaxes*/

// lets create a regex Pattern
def pattern = \~/foo/
assert pattern instanceof Pattern
assert pattern.matcher("foo").matches()

// lets create a Matcher
def matcher = "cheesecheese" =\~ /cheese/
assert matcher instanceof Matcher
answer = matcher.replaceAll("edam")

// lets do some replacement
def cheese = ("cheesecheese" =\~ /cheese/).replaceFirst("nice")
assert cheese == "nicecheese"

// group demo
def matcher = "\$abc." =\~ "\\\$(.*)\\."
matcher.matches(); // must be invoked
assert == "abc"  // is one, not zero
assert matcher[1] == "abc"

The last example can also benefit from the other string literal notation which allows us to avoid having to double all the backslash escaping characters.

Since a Matcher coerces to a boolean by calling its find method, the =~ operator is consistent with the simple use of Perl's =~ operator, when it appears as a predicate (in 'if', 'while', etc.). The "stricter-looking" ==~ operator requires an exact match of the whole subject string.

Regular expression support is imported from Java. Java's regular expression language and API is documented here.

  • No labels