APPENDIX B: Introduction to Groovy 407
Slashy Strings
As mentioned earlier, slashes can be used to define strings. The slashy notation has a nice benefit:
additional backslashes are not needed to escape special characters. The only exception is escaping
a backslash: \/. The slashy notation can be helpful when creating a regular expression requiring
a backslash or a path. Listing B-12 illustrates the difference between using regular quotes and
slashes to define a regular expression to match a file system path.
Listing B-12. Using Slashy Strings
def quotedString = 'Hello Vishal'
def slashyString = /Hello Vishal/
println slashyString
Hello Vishal
Listing B-12 defines two variables and assigns them to a directory path. The first variable definition,
quotedString, uses the single-quote notation to define a string. Using the single-quote notation
requires that the embedded backslash be escaped using an additional backslash.
Multiline Slashy Strings
Slashy strings can also span multiple lines. This is particularly useful for multiline regexes when using
the regex freespacing comment style (see Listing B-13).
Listing B-13. Using Multiline Slashy Strings
- def name = "vishal"
- def path= "c:/groovy"
- def multilineSlashy = /
- Hello $name
- path= $path
- dollar = $
- path = c:\/groovy
- /
- println multilineSlashy
Hello vishal
path= c:/groovy
dollar = $
path = c:/groovy
Let’s take a look at Listing B-13 in a little more detail.
Line 1 defines a variable, name, and assigns the value "vishal" to it.
Line 2 defines a variable, path, and assigns the value "c:/groovy" to it.
Line 3 defines a variable, multilineSlashy, and assigns a multiline string to it
that includes up to line 8, between the slashes.