Chris Beach
Chris Beach

Reputation: 4392

Groovy replaceAll where replacement contains dollar symbol?

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?

Upvotes: 6

Views: 5600

Answers (2)

divonas
divonas

Reputation: 1022

In gradle files to replace use single quotes and double slash:

'\\$bar'

Upvotes: 3

tim_yates
tim_yates

Reputation: 171084

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

Upvotes: 8

Related Questions