Groovy replaceAll where replacement contains dollar symbol?

groovy, regex

Solution

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' ) )

Problem

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?

Original source