Escaping the Dollar Symbol in Groovy [duplicate] - groovy

I need a help in escaping in groovy
I have some string in text file like this #$commonTomcat620.max_threads$# These value i have to replace in runTime.
I used following code:
def str = "#\$commonTomcat620.max_threads\$#"
fileContents = fileContents.replaceAll("${str}","100");
This str is printin the values as #$commonTomcat620.max_threads$#. but not replacing in file. I tried withOut #$ . it is working.
Thanks.

You have a couple of options to escape the dollar sign:
This works (with dollar-slashy strings):
def str = $/#\$$commonTomcat620.max_threads\$$#/$
Or this (with single quote strings):
def str = '#\\$commonTomcat620.max_threads\\$#'
Other options probably exist too

Related

Groovy split on period and return only first value

I have the input as
var = primarynode.domain.local
and now I Need only primarynode from it.
I was looking both split and tokenize but not able to do it in one line code. does anyone know how to do it in one line code?
Well assuming that you want to just get the first word(before . )
from the input string.
You can use the tokenize operator of the String
If you have
def var = "primarynode.domain.local"
then you can do
def firstValue = ​var.tokenize(".")[0]​
println firstValue
output
primarynode
The split method works, you just have to be aware that the argument is a regular expression and not a plain String. And since "." means "any character" in a regular expression, you'll need to escape it...
var = 'primarynode.domain.local'.split(/\./)[0]
...or use a character class (the "." is not special inside a character class)
var = 'primarynode.domain.local'.split(/[.]/)[0]

Replacing a word with $ in groovy

I have the following piece of groovy code from a gradle build file I am using for replacing a word in a php file:
def str1="My application version is $app_version"
def str2 = str1.replaceAll('$app_version','2016072601')
println str2​
I want to replace $app_version with defined number in this method but somehow it is not working. Do I need to escape or do any special action to perform this replacement?
Strings with double quotes and $ are GStrings, which triggers Groovy's string interpolation. Also, replaceAll receives a regex as first argument, and $ is a special character in regex, thus, you need to double escape that too.
You can use single quotes OR you can escape the $ character in your str1:
def str1='My application version is $app_version'
def str2 = str1.replaceAll('\\$app_version','2016072601')
assert str2 == 'My application version is 2016072601'
Update: Expanding string interpolation a bit, it replaces the $ placeholder in your string with the variable value of the same name (though not immediately, as it creates an instance of GString first). It is roughly akin to this in Java:
String str1 = "My application version is " + app_version;
So, instead of replacing the variable with replaceAll, you could have a variable in your script with the name app_version, like def app_version = "2016072601" (which is kinda like #BZ.'s answer)
Update 2: By using string interpolation (as per #BZ.'s answer) or string concatenation, you don't need to use replaceAll, but you need a variable called app_version:
def app_version = '2016072601'
def str1 = "My application version is $app_version"
assert str1 == 'My application version is 2016072601'
And with string concatenation you also need a variable called app_version:
def app_version = '2016072601'
def str1 = "My application version is " + app_version
assert str1 == 'My application version is 2016072601'
Alternately:
def versionString = "2016072601"
def string2 = "My application version is $versionString"

Removing special characters from a string In a Groovy Script

I am looking to remove special characters from a string using groovy, i'm nearly there but it is removing the white spaces that are already in place which I want to keep. I only want to remove the special characters (and not leave a whitespace). I am running the below on a PostCode L&65$$ OBH
def removespecialpostcodce = PostCode.replaceAll("[^a-zA-Z0-9]+","")
log.info removespecialpostcodce
Currently it returns L65OBH but I am looking for it to return L65 OBH
Can anyone help?
Use below code :
PostCode.replaceAll("[^a-zA-Z0-9 ]+","")
instead of
PostCode.replaceAll("[^a-zA-Z0-9]+","")
To remove all special characters in a String you can use the invert regex character:
String str = "..\\.-._./-^+* ".replaceAll("[^A-Za-z0-1]","");
System.out.println("str: <"+str+">");
output:
str: <>
to keep the spaces in the text add a space in the character set
String str = "..\\.-._./-^+* ".replaceAll("[^A-Za-z0-1 ]","");
System.out.println("str: <"+str+">");
output:
str: < >

groovy replace double quotes with single and single with double

I have a string "['type':'MultiPolygon', 'coordinates':[[73.31, 37.46], [74.92, 37.24]]]"
How can I replace all single quotes with double quotes and double to with single?
The result should be like this:
'["type":"MultiPolygon", "coordinates":[[73.31, 37.46], [74.92, 37.24]]]'
From link given by #yate, you can find a method:
tr(String sourceSet, String replacementSet)
and apply that to your string as:
def yourString = ...
def changedString = yourString.tr(/"'/,/'"/)
that will do the job.
You want to use the replaceAll method. Since the first conversion will be overridden by the second, you may need a temporary variable:
String replacePlaceholder = '%%%' // Some unlikely-to-occur value
yourString = yourString.replaceAll('\'', replacePlaceholder)
.replaceAll('"', '\'')
.replaceAll(replacePlaceholder, '"')
It's certainly not the most efficient way to do it, but it's a start.

illegal string body character after dollar sign

if i define a groovy variable
def x = "anish$"
it will throw me error, the fix is
def x = "anish\$"
apart form "$" what are the blacklist characters that needs to be backslash,Is there a Groovy reference that lists the reserved characters. Most “language specifications” mention these details, but I don’t see it in the Groovy language spec (many “TODO” comments).
Just use single quotes:
def x = 'anish$'
If this isn't possible, the only thing that's going to cause you problems is $, as that is the templating char used by GString (see the GString section on this page -- about half way down)
Obviously, the backslash char needs escaping as well, ie:
def x = 'anish\\'
You can use octal representation. the character $ represents 044 in octal, then:
def x = 'anish\044'
or
def x = 'anish\044'
For example, in Java i did use like this:
def x = 'anish\044'
If you wants knows others letters or symbols converters, click here :)
The solution from tim_yates does not work in some contexts, e.g. in a Jasper report.
So if still everything with a $ sign wants to be interpreted as some variable (${varX}), e.g. in
"xyz".replaceAll("^(.{4}).{3}.+$", "$1...")
then simply make the dollar sign a single concatenated character '$', e.g.
"xyz".replaceAll("^(.{4}).{3}.+"+'$', '$'+"1...")
It might be a cheap method, but the following works for me.
def x = "anish" + '$'
Another alternative that is useful in Groovy templating is ${'$'}, like:
def x = "anish${'$'}" // anish$
Interpolate the Java String '$' into your GString.

Resources