Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 66 ]

You can find JavaDoc under the class documentation for java.util.regex.Pattern.
The following is a truncated list of some of the more commonly-used patterns:


Construct Matches

. Any character
^ The start of a line
$ The end of a line
X The character x
\d A digit character
\D Any character except a digit
\s A whitespace character
\S Any character except whitespace
\w A word character
\W Any character except word characters
\b A word boundary
(x|y|z) x or y or z, that is, (apple|orange|pear)
[a-f] The character class containing any character between a and f
[abc] a, b, or c


The Groovy find operator (=~) is similar to match but returns a
java.util.regex.Matcher object. In the following code, we use find
to return a matcher for all three-letter words with a middle letter of o. The
pattern we use is /\b.o.\b/. Groovy allows us to use the collection convenience
method "each" to iterate over the resulting matches and invoke a closure on each
match to output the result. There will be more on collections and closures shortly:


given: "A String with words we want to match"
def quickBrownFox =
"The quick brown fox jumps over the lazy dog."
and: "a matcher built via the find operator"
def matcher = quickBrownFox =~ /\b.o.\b/
expect: "to match all three letter words with middle letter o"
matcher.findAll() == ['fox','dog']

http://www.ebook3000.com
Free download pdf