Groovy Goodness: Using Regular Expression Pattern Class

To define a regular expression pattern in Groovy we can use the tilde (~) operator for a String. The result is a java.util.regex.Pattern object. The rules to define the pattern are the same as when we do it in Java code. We can invoke all standard methods on the Pattern object. For example we can create a Matcher to match values. In a next blog post we see how Groovy has better shortcuts to define a Matcher to find and match values.

00.def single = ~'[ab]test\\d'
01.assert 'java.util.regex.Pattern' == single.class.name
02. 
03.def dubble = ~"string\$"
04.assert dubble instanceof java.util.regex.Pattern
05. 
06.// Groovy's String slashy syntax is very useful to
07.// define patterns, because we don't have to escape
08.// all those backslashes.
09.def slashy = ~/slashy \d+ value/
10.assert slashy instanceof java.util.regex.Pattern
11. 
12.// GString adds a negate() method which is mapped
13.// to the ~ operator.
14.def negateSlashy = /${'hello'}GString$/.negate()
15.assert negateSlashy instanceof java.util.regex.Pattern
16.def s = 'more'
17.def curlySlashy = ~"$s GString"
18.assert curlySlashy instanceof java.util.regex.Pattern
19. 
20.// Using Pattern.matcher() to create new java.util.regex.Matcher.
21.// In a next blog post we learn other ways to create
22.// Matchers in Groovy.
23.def testPattern = ~'t..t'
24.assert testPattern.matcher("test").matches()
25. 
26.// Groovy adds isCase() method to Pattern class.
27.// Easy for switch and grep statements.
28.def p = ~/\w+vy/
29.assert p.isCase('groovy')
30. 
31.switch ('groovy') {
32.case ~/java/: assert false; break;
33.case ~/gr\w{4}/: assert true; break;
34.default: assert false
35.}
36. 
37.// We can use flags in our expressions. In this sample
38.// we use the case insensitive flag (?i).
39.// And the grep method accepts Patterns.
40.def lang = ~/^(?i)gr.*/
41.def languages = ['java', 'Groovy', 'gRails']
42.assert ['Groovy', 'gRails'] == languages.grep(lang)