Writing regular Expressions (regexes) in groovy is a pleasure compared to Java. In Java, regexes programming requires not only the processing of pattern and Matcher objects, but also the writing of tedious boilerplate code (boilerplate coding). Groovy does a simple encapsulation of these two Java objects, adds some additional practical methods, and gives a simplified new syntax and 3 new operators.
In groovy, you can use Slashy (slash) syntax "/.. /"defines a string. This avoids the use of too many backslashes in Java regular expressions. For example:
ASSERT (/hello world/in String)
ASSERT (/hi \there/= = ' Hi \\there ')
The 1th new regular expression operator in groovy is the pattern operator (~), which causes the string to be compiled into an instance of patterns. For example:
p = ~/\b[a-za-z]\b/
You can also use Java implementations, such as:
Import java.util.regex.*
Pattern p = pattern.compile ("\\b[a-za-z]\\b");
The common regular expression patterns and meanings are listed in Table 3.1. A complete regular expression manifest can refer to the Pattern API documentation, http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html.
Table 3.1 Common Regular expression patterns
Pattern meaning
A?
Match as many as 1 times a, or you can not match
A *
expression as much as possible to match a, at least not match
A +
Match A as much as possible and match at least 1 times
A|b
Match A or B
(AB)
Group
.
Match any one character
[ABC]
Match A,b or C
[^ABC]
Match any one character except A,b or C
[A-z]
Match any letter between A and Z