English 中文(简体)
Groovy 替换所有 替换的地方 含有美元符号?
原标题:Groovy replaceAll where replacement contains dollar symbol?
  • 时间:2012-05-25 14:15:59
  •  标签:
  • regex
  • groovy

我在格罗维使用 replaceall () in Groovy, 当替换字符串包含 $ 符号( 被解释为regexm群集引用) 时, 就会被捕获 。

我发现我不得不做一个相当丑陋的 双重替代:

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

此处:

replacement = "$bar"

预期成果是:

replaced = "$bar"

是否有更好的方法在没有中间步骤的情况下进行这种替换?

最佳回答

docs 代替All 所述,您可以使用 Matcher.quotteReplace

def input = "You must pay %price%"

def price =  $41.98 

input.replaceAll  %price% , java.util.regex.Matcher.quoteReplacement( price )

2. 还注意到以下各段不是重复引用:

replacement = "$bar"

您想要使用单引号, 例如 :

replacement =  $bar 

否则Groovy将把它当作模板处理, 当找不到属性 bar 时失败

举例来说:

import java.util.regex.Matcher
assert  $bar  ==  foo .replaceAll(  foo , Matcher.quoteReplacement(  $bar  ) )
问题回答

在用于替换单引数和双斜线的 gradle 文件中 :

 \$bar 




相关问题
Uncommon regular expressions [closed]

Recently I discovered two amazing regular expression features: ?: and ?!. I was curious of other neat regex features. So maybe you would like to share some tricky regular expressions.

regex to trap img tag, both versions

I need to remove image tags from text, so both versions of the tag: <img src="" ... ></img> <img src="" ... />

C++, Boost regex, replace value function of matched value?

Specifically, I have an array of strings called val, and want to replace all instances of "%{n}%" in the input with val[n]. More generally, I want the replace value to be a function of the match ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

Is it possible to negate a regular expression search?

I m building a lexical analysis engine in c#. For the most part it is done and works quite well. One of the features of my lexer is that it allows any user to input their own regular expressions. This ...

regex for four-digit numbers (or "default")

I need a regex for four-digit numbers separated by comma ("default" can also be a value). Examples: 6755 3452,8767,9865,8766,3454 7678,9876 1234,9867,6876,9865 default Note: "default" ...

热门标签