Replace all occurrences in a String by using regex in groovy

groovy, multiple-matches, regex

Solution

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'

Problem

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

Original source