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: \!\"\@\#\$\%\&\/\(\)\=\?
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.