Groovy replaceAll哪里有替换包含美元符号?

Chr*_*ach 6 regex groovy

replaceAll()在Groovy中使用并在替换字符串包含$符号(被解释为正则表达式组引用)时被捕获.

我发现我必须做一个相当丑陋的双重替换:

def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$')
replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement)
Run Code Online (Sandbox Code Playgroud)

哪里:

replacement = "$bar"
Run Code Online (Sandbox Code Playgroud)

期望的结果是:

replaced = "$bar"
Run Code Online (Sandbox Code Playgroud)

没有中间步骤,是否有更好的方法来执行此替换?

tim*_*tes 8

正如在replaceAll文档中所述,您可以使用Matcher.quoteReplacement

def input = "You must pay %price%"

def price = '$41.98'

input.replaceAll '%price%', java.util.regex.Matcher.quoteReplacement( price )
Run Code Online (Sandbox Code Playgroud)

另请注意,而不是双引号:

replacement = "$bar"
Run Code Online (Sandbox Code Playgroud)

你想使用单引号,如:

replacement = '$bar'
Run Code Online (Sandbox Code Playgroud)

否则,Groovy会将其视为模板,并在无法找到属性时失败 bar

所以,举个例子:

import java.util.regex.Matcher
assert '$bar' == 'foo'.replaceAll( 'foo', Matcher.quoteReplacement( '$bar' ) )
Run Code Online (Sandbox Code Playgroud)