在Groovy中转义特殊字符的正则表达式

3

我正在尝试使用正则表达式来转义特殊字符,现在已经在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: \!\"\@\#\$\%\&\/\(\)\=\?
1个回答

2
请注意,[\W|_] = [\W_],因为|是一个非单词字符。此外,建议使用斜杠字符串定义正则表达式,因为它们内部的反斜杠表示文本中的反斜杠,这些反斜杠用于形成正则表达式转义字符
看起来您不想匹配空格,因此需要从[\W_]中减去\s,使用/[\W_&&[^\s]]/正则表达式。
其次,在替换部分,您可以使用单引号字符串字面值来避免插值$0
.replaceAll(specialCharRegex, '\\\\$0')

否则,在双引号字符串文字中,需要转义 $

.replaceAll(specialCharRegex, "\\\\\$0")

斜杠字符串也能按预期工作:
.replaceAll(specialCharRegex, /\\$0/)

查看在线 Groovy 演示

String specialCharRegex = /[\W_&&[^\s]]/;                                 
println('test 1& test'.replaceAll(specialCharRegex, '\\\\$0'));           // test 1\& test
println('test 1& test 2$'.replaceAll(specialCharRegex, "\\\\\$0"));       // test 1\& test 2\$
println('test 1& test 2$ test 3%'.replaceAll(specialCharRegex, /\\$0/));  // test 1\& test 2\$ test 3\%
println('!"@#$%&/()=?'.replaceAll(specialCharRegex, /\\$0/));             // \!\"\@\#\$\%\&\/\(\)\=\?

在 ideon.com 上,即使我发布了带有错误的代码,也能够完美运行。可能是我尝试的其他页面出了问题。您能否查看一下并从以下链接提供帮助:https://stackoverflow.com/questions/51159593/how-to-run-groovy-in-java。我正在尝试在 Java(main)中运行来自 Groovy 类的方法。 - Dr3ko
使用除了“引号”以外的任何东西来分隔字符串似乎很奇怪,但我猜这是 Groovy 魔法 DSL 的一部分。(自从我 Perl 古老的日子以来就没有看到过 /regex/ 斜杠。) - MarkHu
@MarkHu 你可以在这里了解有关slashy strings的更多信息。甚至还有更高级的dollar slashy strings,其中你不必转义/$。 :) - Wiktor Stribiżew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接