regex - Groovy replaceAll 替换包含美元符号的地方?

标签 regex groovy

我正在使用 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/

相关文章:

Grails SpringSecurity 用户对象

java - 无法从 ReactiveCouchbaseRepository 中删除项目

orm - GORM继承问题

java - 用管道字符 ("|"分割字符串)

python - python中获取以下模式字符串的方法

C# - 从 List3 中删除 List1 和 List2 中的项目时出现问题

java正则表达式

python - 将具有相似(但略有不同)子字符串的字符串重新映射到相同的结果

java - 如何通过 Spock 测试进行 CDI/SE?

groovy - 这种 groovy 语法如何转换为 kotlin?