Loading...

Tuesday, April 28, 2009

Escaping quotes in Groovy strings

Groovy supports strings enclosed in single or double quotes and between slashes. If we use single quotes we don't have to escape double quotes. And if we use double quotes we don't have to escape single quotes. We can use the slashes if we have a string with both double and single quotes and we don't want to escape them.

def singleQuote = 'Single quote string to "demo" double quotes without backslash escape.'
def doubleQuote = "Double quote string let's us use single quote without backslash escape."
def slashy = /Slashy string let's us use single and "double" quotes without backslash escapes./

println singleQuote
println doubleQuote
println slashy

When we run this Groovy script we get the following output:

Single quote string to "demo" double quotes without backslash escape.
Double quote string let's us use single quote without backslash escape.
Slashy string let's us use single and "double" quotes without backslash escapes.

3 comments:

Lucas Teixeira said...

Excellent mrhaki!!

We should just remember that using single quoted strings, we're not creating GStrings but only Strings, that will not let us to use others var inside it.

def name = "Lucas"
def firstLine = "Hello, my name is ${name}."
def secondLine = 'Hello, my name is ${name}.'

println firstLine
println secondLine

:]

paulk said...

You can also use the multi-line quotes even if you don't have multiple lines, e.g.:

def warning = '''don't'''
println warning

This can sometimes be handy.

paulk said...

Previous example has three single quotes on either side of the don't word in case the font makes it hard to read. (Couldn't work out how to put it into code font mode)

Post a Comment