我正在使用 replaceAll()
在 Groovy 中并在替换字符串包含 $
时被发现符号(被解释为正则表达式组引用)。
我发现我必须做一个相当丑陋的双重替换:
def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$')
replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement)
在哪里:
replacement = "$bar"
期望的结果是:
replaced = "$bar"
在没有中间步骤的情况下,是否有更好的方法来执行此替换?
最佳答案
正如 docs for 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' ) )
关于regex - Groovy replaceAll 替换包含美元符号的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10756016/