Groovy

Using Groovy

Language Guide

Groovy Features

Modules

Examples

Useful Links

IDE Support

Support

Community

Developers

Tools we use

IntelliJ IDEA
YourKit profiler

Feeds


Site
News
Regular Expressions

Groovy supports regular expressions natively using the ~"..." expression. Plus Groovy supports the =~ (create Matcher) and ==~ (matches regex) operators. e.g.

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

assert "cheesecheese" =~ "cheese"

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

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

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

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.

(It would be nice to supply other Perl amenities, such as !~ and in-place edits of string variables. This is a job for someone familiar with the range of use cases, and their expressions in terms of Java Matchers. – John Rose.)