How to escape special characters with Groovy

Jesus Enrique Diaz Burgos July 3, 2018

Hi everyone, I'm trying to use a regex to scape special characters, right now used it on Java and works perfect, it does exactly what I want `Scape any special character` however I tried this in Groovy but the same line doesn't work, as far I investaged it's because `$` is reserved in Groovy, so far I tried this;


Java: (Does the job)

String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, "\\\\$0");
...

Groovy:

error

String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, "\\\\$0");
...

error

String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, "\\\\\$0");
...

error

String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, '\\\\$0');
...

error

String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, '\\\\$1');
...

I use `https://groovyconsole.appspot.com/` to test it.

Output in Groovy should be:

Input: test 1& test
Output: test 1\& test

Input: test 1& test 2$
Output: test 1\& test 2\$

Input: test 1& test 2$ test 3%
Output: test 1\& test 2\$ test 3\%

Input: !"@#$%&/()=?
Output: \!\"\@\#\$\%\&\/\(\)\=\?

1 answer

0 votes
Andrew
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
April 24, 2019

Hi @Jesus Enrique Diaz Burgos ,

Works for me:

String test = "1& test 2\$ test 3% !\"@#\$%&/()=?"

result = test.replaceAll(/(!|"|@|#|\$|%|&|\\/|\(|\)|=|\?)/, /\\$0/)

println(result)

output:

> String test = "1& test 2\$ test 3% !\"@#\$%&/()=?"
>
> result = test.replaceAll(/(!|"|@|#|\$|%|&|\\/|\(|\)|=|\?)/, /\\$0/)
>
> println(result)
1\& test 2\$ test 3\% \!\"\@\#\$\%\&\/\(\)\=\?


B.R.

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events