Regex Groovy replaceAll替换包含美元符号的位置?
我在Groovy中使用Regex Groovy replaceAll替换包含美元符号的位置?,regex,groovy,Regex,Groovy,我在Groovy中使用replaceAll(),当替换字符串包含$符号(它被解释为regexp组引用)时,我会被发现 我发现我必须做一个相当丑陋的双重替换: def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$') replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement) 其中: replacement = "$bar" 期望的结果是: replac
replaceAll()
,当替换字符串包含$
符号(它被解释为regexp组引用)时,我会被发现
我发现我必须做一个相当丑陋的双重替换:
def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$')
replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement)
其中:
replacement = "$bar"
期望的结果是:
replaced = "$bar"
是否有更好的方法在不使用中间步骤的情况下执行此替换?如中所述,您可以使用Matcher.quoteReplacement
def input = "You must pay %price%"
def price = '$41.98'
input.replaceAll '%price%', java.util.regex.Matcher.quoteReplacement( price )
还请注意,在下列情况下,不要使用双引号:
replacement = "$bar"
您希望使用单引号,如:
replacement = '$bar'
否则,Groovy将把它当作模板,当它找不到属性bar
以你为例:
import java.util.regex.Matcher
assert '$bar' == 'foo'.replaceAll( 'foo', Matcher.quoteReplacement( '$bar' ) )
在要替换的渐变文件中,请使用单引号和双斜杠:
'\\$bar'
您的输入字符串是什么?您希望输出什么?如何指定要在其中执行此替换的文件?