Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy replaceAll where replacement contains dollar symbol?

Tags:

regex

groovy

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?

like image 666
Chris Beach Avatar asked May 25 '12 14:05

Chris Beach


2 Answers

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' ) )
like image 94
tim_yates Avatar answered Sep 19 '22 00:09

tim_yates


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

'\\$bar'
like image 30
divonas Avatar answered Sep 20 '22 00:09

divonas