6

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

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

def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$')
replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement)

在哪里:

replacement = "$bar"

期望的结果是:

replaced = "$bar"

是否有更好的方法来执行此替换而无需中间步骤?

4

2 回答 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' ) )
于 2012-05-25T14:29:11.650 回答
1

在 gradle 文件中替换使用单引号和双斜杠:

'\\$bar'
于 2017-05-05T10:21:30.983 回答