Groovy replaceAll, where does the replacement contain a dollar sign?

I use replaceAll() in Groovy and get it when the replacement string contains the $ character (which is interpreted as a regexp group link).

I find that I need to do a pretty ugly double replacement:

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

Where:

 replacement = "$bar" 

And the desired result:

 replaced = "$bar" 

Is there a better way to do this replacement without an intermediate step?

+6
source share
2 answers

As the docs say for replaceAll , you can use Matcher.quoteReplacement

 def input = "You must pay %price%" def price = '$41.98' input.replaceAll '%price%', java.util.regex.Matcher.quoteReplacement( price ) 

Also note that instead of double quotes in:

 replacement = "$bar" 

You want to use single quotes, for example:

 replacement = '$bar' 

Otherwise, Groovy will treat it as a template and fail if it cannot find the bar property.

So for your example:

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

In gradle files, use single quotes and double slashes to replace:

 '\\$bar' 
0
source

Source: https://habr.com/ru/post/916676/


All Articles