I'm using replaceAll()
in Groovy and getting caught out when the replacement string contains the $
symbol (which is interpreted as a regexp group reference).
I'm finding I have to do a rather ugly double replacement:
def regexpSafeReplacement = replacement.replaceAll(/\$/, '\\\\\\$')
replaced = ("foo" =~ /foo/).replaceAll(regexpSafeReplacement)
Where:
replacement = "$bar"
And desired result is:
replaced = "$bar"
Is there a better way of performing this replacement without the intermediate step?
As it says in the docs 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 like:
replacement = '$bar'
As otherwise Groovy will treat it as a template and fail when it can't find the property bar
So, for your example:
import java.util.regex.Matcher
assert '$bar' == 'foo'.replaceAll( 'foo', Matcher.quoteReplacement( '$bar' ) )
In gradle files to replace use single quotes and double slash:
'\\$bar'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With