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.quoteReplacementAlso note that instead of double quotes in:
You want to use single quotes like:
As otherwise Groovy will treat it as a template and fail when it can’t find the property
barSo, for your example: