Regex 在Groovy中转义特殊字符的正则表达式
我正在尝试使用正则表达式替换特殊字符,现在在Java上使用它,效果非常好,它完全符合我的要求Regex 在Groovy中转义特殊字符的正则表达式,regex,groovy,Regex,Groovy,我正在尝试使用正则表达式替换特殊字符,现在在Java上使用它,效果非常好,它完全符合我的要求替换任何特殊字符,但是我在Groovy中尝试了这一点,但同一行不起作用,据我所知,这是因为$在Groovy中是保留的,到目前为止,我尝试了这一点 爪哇:(做这项工作) Groovy: 错误 错误 错误 错误 我使用https://groovyconsole.appspot.com/来测试它 Groovy中的输出应为: Input: test 1& test Output: test 1\&
替换任何特殊字符
,但是我在Groovy中尝试了这一点,但同一行不起作用,据我所知,这是因为$
在Groovy中是保留的,到目前为止,我尝试了这一点
爪哇:(做这项工作)
Groovy:
错误
错误
错误
错误
我使用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: \!\"\@\#\$\%\&\/\(\)\=\?
请注意,
[\W|
=[\W|]
,因为
是非单词字符。此外,建议使用斜杠字符串定义正则表达式,因为其中的反斜杠表示文字反斜杠,即用于形成正则表达式转义的反斜杠
似乎您不想匹配空格,因此需要从[\W\u]
中减去\s
,使用/[\W\u&&[^\s]]/
正则表达式
其次,在替换部分中,可以使用单引号字符串文字来避免插入$0
:
.replaceAll(specialCharRegex, '\\\\$0')
否则,在双引号字符串文本中转义$
:
.replaceAll(specialCharRegex, "\\\\\$0")
斜线字符串也可以按预期工作:
.replaceAll(specialCharRegex, /\\$0/)
见:
在ideon.com上,即使是我发布的那些有错误的页面,也工作得非常完美,这可能是我尝试的另一个页面。如果可能的话,你能从这张照片上看一看并提供帮助吗;试图在Java(main)中运行Groovy类的方法。使用“引号”以外的任何东西来分隔字符串似乎很奇怪,但我想这是Groovy magic DSL的一部分。(自从我以前使用Perl以来,就没有见过
/regex/
斜杠。)@MarkHu您可以了解更多。甚至还有一些爱好者,你不必逃避/
和$
:)
String specialCharRegex = "[\\W|_]";
...
term = term.replaceAll(specialCharRegex, '\\\\$1');
...
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: \!\"\@\#\$\%\&\/\(\)\=\?
.replaceAll(specialCharRegex, '\\\\$0')
.replaceAll(specialCharRegex, "\\\\\$0")
.replaceAll(specialCharRegex, /\\$0/)
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/)); // \!\"\@\#\$\%\&\/\(\)\=\?