6

当只有一次出现时,我的代码有效:

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

如果我的字符串包含多次出现,我该怎么办?

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

谢谢

4

1 回答 1

16

您可以将上述内容替换为:

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

或者,您可以这样做:

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'
于 2013-12-05T10:17:59.467 回答