Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences in a String by using regex in groovy

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

like image 891
Jils Avatar asked Dec 05 '13 10:12

Jils


1 Answers

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'
like image 180
tim_yates Avatar answered Sep 19 '22 01:09

tim_yates