微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – Groovy replaceAll替换包含美元符号?

我在Groovy中使用replaceAll()并在替换字符串包含$符号(被解释为 regexp组引用)时被捕获.

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

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会将其视为模板,并在无法找到属性栏时失败

所以,举个例子:

import java.util.regex.Matcher
assert '$bar' == 'foo'.replaceAll( 'foo',Matcher.quoteReplacement( '$bar' ) )

原文地址:https://www.jb51.cc/regex/356559.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐