Groovy supports regular expressions natively using the ~"pattern" expression, which creates a compiled Java Pattern object from the given pattern string. Groovy also supports the =~ (create Matcher) and ==~ (returns boolean, whether String matches the pattern) operators.
For matchers having groups, matcher[index] is either a matched String or a List of matched group Strings.
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 returns a Boolean, not a Matcher.
Regular expression support is imported from Java. Java's regular expression language and API is documented here in the Pattern JavaDocs.
More Examples
Goal: Capitalize words at the beginning of each line:
Goal: Capitalize every word in a string:
Add .toLowerCase() to make the rest of the words lowercase
Gotchas
How to use backreferences with String.replaceAll()
GStrings do not work as you'd expect:
Produces an error like the following:
[] illegal string body character after dollar sign:
solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line []
Solution:
Use ' or / to delimit the replacement string:
2 Comments
Hide/Show CommentsDec 17, 2010
miles zarathustra
An easier way to uppercase all of the first letters.
N.B an authentic title case skips prepositions.
Why use
?
This does the same thing more simply (because we can assume that it.size>0)
Jun 22, 2011
Michael Smith
Was trying out some of the above code:
// lets create a Matcher
def matcher = "cheesecheese" =~ /cheese/
assert matcher instanceof Matcher
The assertion statement is always true, no matter what the string or the pattern is set to.
E.g., this works too
// lets create a Matcher
def matcher = "nothing" =~ /cheese/
assert matcher instanceof Matcher
Maybe this is the point of the assertion to show that a Matcher is automatically create behind the scenes based on the statement?