加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 22:53:40 所属栏目:百科 来源:网络整理
导读:我在Groovy中使用replaceAll()并在替换字符串包含$符号(被解释为 regexp组引用)时被捕获. 我发现我必须做一个相当丑陋的双重替换: def regexpSafeReplacement = replacement.replaceAll(/$/,'\$')replaced = ("foo" =~ /foo/).replaceAll(regexpSafeR
我在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' ) )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读