Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 65 ]

The final assertion shown in the preceding code introduces yet another Groovy
string syntax, which goes under the name slashy strings. Slashy strings are most
commonly used when defining regex strings, but they can be used anywhere you
wish to define a string object.


The biggest advantage of the slashy string is the fact that the backslash character
\ does not need to be escaped. In a literal string, \ is a single backslash. So, to place
the character class \d in a string literal, we need to write \d. To match the backslash
character itself, we need to write \\. In slashy string format, these become /\d/
and /\/ respectively.


A further refinement was added to slashy strings in Groovy 1.8. Dollar slashy strings
are denoted by a starting $/ and ending /$ and have different escaping rules to the
regular GStrings. Slash and backslash do not need to be escaped. However, $ can be
used as an escape if needed. The differences are best illustrated with an example:


given: "a dollar slashy"
def dollarSlashy = $/
$ dollar
$$ dollar
\ backslash
/ slash
$/ slash
/$
and: "an old style multiline string"
def multi = """
\$ dollar
\$ dollar
\\ backslash
/ slash
/ slash
"""
expect:
multi == dollarSlashy

Groovy adds some neat usability features to Java regular expression handling,
but under the covers, it still uses the java.util.regex classes. Groovy regex
pattern strings are identical to their Java equivalents. The most comprehensive
documentation for all of the pattern options available can be found in your Java SE.

Free download pdf