Replace all occurrences in a String by using regex in groovy

Jils picture Jils · Dec 5, 2013 · Viewed 13.3k times · Source

When there are only one occurrence my code works:

def result = "Text 1,1"
def matches = (result =~ /^.+\s([0-9],[0-9])$/ ).with { m -> m.matches() ? result.replace(/${m[ 0 ][ 1 ]}/, 'X'+m[ 0 ][ 1 ]+'X') : result }
assert "Text X,X" == matches

How can I do if my String contains several occurrences?

def result = "aaaa Text 1,1 Text 2,2 ssss"

Thanks

Answer

tim_yates picture tim_yates · Dec 5, 2013

You could replace the above with:

def matches = result.replaceAll( /[0-9],[0-9]/, 'X,X' )

Or, you could do:

def result = "aaaa Text 1,1 Text 2,2 ssss"

result = result.replaceAll( /[0-9],[0-9]/ ) { m -> "X${m}X" }

assert result == 'aaaa Text X1,1X Text X2,2X ssss'