我正在尝试使用正则表达式来转义特殊字符,现在已经在Java上使用它并完美地发挥作用,它恰好做我想要做的事情转义任何特殊字符
。然而,我在Groovy中尝试了这个正则表达式但是同样的代码行不起作用。据我所调查,这是因为在Groovy中$
被保留,到目前为止我尝试了这些方法:
Java:(完成任务)
String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, "\\\\$0");
...
Groovy:
错误
String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, "\\\\$0");
...
错误
String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, "\\\\\$0");
...
错误
String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, '\\\\$0');
...
错误
String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, '\\\\$1');
...
我使用 https://groovyconsole.appspot.com/
进行测试。
Groovy 中的输出应该是:
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: \!\"\@\#\$\%\&\/\(\)\=\?
/regex/
斜杠。) - MarkHu/
和$
。 :) - Wiktor Stribiżew