在groovy中使用正则表达式替换String中的所有匹配项
发布时间:2020-12-14 16:28:58 所属栏目:大数据 来源:网络整理
导读:当我的代码只有一次出现时: 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 如果我的String包含多次
当我的代码只有一次出现时:
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 如果我的String包含多次出现,我该怎么办? def result = "aaaa Text 1,1 Text 2,2 ssss" 谢谢 解决方法
您可以将以上内容替换为:
def matches = result.replaceAll( /[0-9],[0-9]/,'X,X' ) 或者,您可以这样做: def result = "aaaa Text 1,2 ssss" result = result.replaceAll( /[0-9],[0-9]/ ) { m -> "X${m}X" } assert result == 'aaaa Text X1,1X Text X2,2X ssss' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |