Search code examples
groovyjenkins-groovygroovy-console

Replace in groovy a string in path with another string


I will like to replace from:

"stable_dev/201904_xx/text1/text2.zip"
"stable_dev/201904/text5/text6.war"

into:

"stable_dev/new_value/text1/text2.zip"
"stable_dev/new_value/text5/text6.war"
I tried with

arrayList.toString().replaceAll("stable_dev/"+"[0-9a-zA-Z]*"+"[^a-zA-Z0-9]*"+"[0-9a-zA-Z]*"+"/", "stable_dev/new_value/"))

Solution

  • This is only specific to your examples. Idea is to search for stable_dev/ and then locate everything till the next / Then replace that with the new value.

    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​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​