The regular expression API became part of JDK since v1.4. Pattern
,
Matcher
, and String
classes contain functionality for regular expression matching and replacement that may not always be obvious, especially for complex use cases.
Luckily, Groovy adds some syntax sugar and functionality to support regular expressions in a more native fashion that will be demonstrated in this recipe.
We assume that you already have familiarity with regular expressions. This recipe will only focus on the features added by Groovy to the already rich infrastructure offered by Java to deal with regular expressions.
To begin with, Groovy offers a simple way to create Pattern
objects using the ~/pattern/
notation:
Pattern pattern = ~/^.*?groovy.*$/
The previous pattern will match any text that contains the word groovy
in it.
In fact, slashes at the beginning and the end of a pattern represent an alternative way to define strings in Groovy. The following...