Dollar-Slashy Strings in Groovy [Ver 1.8+]

25 / Sep / 2012 by Kushal Likhi 0 comments

Hi,

 

Groovy took another leap ahead in the methodology of defining Strings by providing us with “dollar-slashy” strings which further minimized the need of escaping any special character as compared to simple “slashy” Strings.

 

In the Groovy ver:1.8+ you can define Strings as follows:
[java]
//A dollar-slashy string
String message = $/Hi! I am Kushal Likhi!/$

println message
//Output: Hi! I am Kushal Likhi!
[/java]

 

In the above example we saw that string is defined by using a dollar-Slash combination. The biggest advantage of this combination is that we don’t even have to escape slashes(“/”), which results in a cleaner better code.

 

Dollar-slashy strings can be best used with regular expressions as it will enable us to write much cleaner regular expressions.
An example of regular expression to find the protocol of the URL.
[java]
//Using simple slashy strings
String protocol = "http://www.intelligrape.com".find(/([^\/]+):\/\//){it[1]}
assert protocol == "http" //will be true

//Now using dollar slashy Strings we can implement the same functionality by:
String protocol = "http://www.intelligrape.com".find($/([^/]+):///$){it[1]}
assert protocol == "http" //will be true

//You can see that we have a much CLEANER RegEx using dollar slashy strings.
[/java]

 

 

Hope it helps!
Kushal Likhi

FOUND THIS USEFUL? SHARE IT

Tag -

Groovy

Leave a Reply

Your email address will not be published. Required fields are marked *