将 groovy 路径中的一个字符串替换为另一个字符串
Replace in groovy a string in path with another string
我想替换为:
"stable_dev/201904_xx/text1/text2.zip"=24=]
"stable_dev/201904/text5/text6.war"
进入:
"stable_dev/new_value/text1/text2.zip"=24=]
"stable_dev/new_value/text5/text6.war"
我试过
arrayList.toString().replaceAll("stable_dev/"+"[0-9a-zA-Z]*"+"[^a-zA-Z0-9]*"+"[0-9a-zA-Z]*"+"/", "stable_dev/new_value/"))
我会使用 split
来避免过于复杂的正则表达式:
def replacer = { String replacement, String val ->
def parts = val.split( /\d{6}_?([a-z0-9]{2})?/ )
2 != parts.size() ? val : "${parts[ 0 ]}$replacement${parts[ 1 ]}"
}
def results = [
'aaa',
"stable_dev/201904_xx/text1/text2.zip",
"stable_dev/201904/text5/text6.war"
].collect replacer.curry( 'new_value' )
assert results == [ 'aaa', 'stable_dev/new_value/text1/text2.zip', 'stable_dev/new_value/text5/text6.war' ]
这仅针对您的示例。想法是搜索 stable_dev/
然后找到所有内容直到下一个 /
然后用新值替换它。
def str = "stable_dev/201904_xx/text1/text2.zip"
println str.replaceAll(/stable_dev\/.*?\//,"stable_dev/new_value/")
//Output:
//stable_dev/new_value/text1/text2.zip
我想替换为:
"stable_dev/201904_xx/text1/text2.zip"=24=] "stable_dev/201904/text5/text6.war"
进入:
"stable_dev/new_value/text1/text2.zip"=24=]
"stable_dev/new_value/text5/text6.war"
我试过
arrayList.toString().replaceAll("stable_dev/"+"[0-9a-zA-Z]*"+"[^a-zA-Z0-9]*"+"[0-9a-zA-Z]*"+"/", "stable_dev/new_value/"))
我会使用 split
来避免过于复杂的正则表达式:
def replacer = { String replacement, String val ->
def parts = val.split( /\d{6}_?([a-z0-9]{2})?/ )
2 != parts.size() ? val : "${parts[ 0 ]}$replacement${parts[ 1 ]}"
}
def results = [
'aaa',
"stable_dev/201904_xx/text1/text2.zip",
"stable_dev/201904/text5/text6.war"
].collect replacer.curry( 'new_value' )
assert results == [ 'aaa', 'stable_dev/new_value/text1/text2.zip', 'stable_dev/new_value/text5/text6.war' ]
这仅针对您的示例。想法是搜索 stable_dev/
然后找到所有内容直到下一个 /
然后用新值替换它。
def str = "stable_dev/201904_xx/text1/text2.zip"
println str.replaceAll(/stable_dev\/.*?\//,"stable_dev/new_value/")
//Output:
//stable_dev/new_value/text1/text2.zip