Groovy中的replaceAll函数如何替换包含美元符号的字符串?

6
我正在使用Groovy中的replaceAll(),当替换字符串包含$符号时(被解释为正则表达式组引用),我会遇到问题。
我发现我不得不进行相当丑陋的双重替换:
def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$')
replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement)

场景:

replacement = "$bar"

And desired result is:

replaced = "$bar"

有没有更好的方法在不使用中间步骤的情况下执行此替换?

你的输入字符串是什么,你期望得到什么输出? - tim_yates
2个回答

8

如在replaceAll文档中所述,您可以使用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' ) )

你如何指定要进行替换的文件? - IgorGanapolsky

3

在Gradle文件中,使用单引号和双斜杠进行替换:

'\\$bar'

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