groovyjenkins-groovy

How do I extract a specific number from a string / url using groovy?


I am trying to extract a specific number(without any special characters) from a url/string using groovy script.

ABC/MyABC/XYZ/POC-xyz-api-oci #89

In the above string, I want to extract only the number 89 without any special characters using groovy script. How can it be done?

I tried something like below:

    def build_numb = "ABC/MyABC/XYZ/POC-xyz-api-oci #89"

//    def cleanedString = build_numb.replaceAll(/[^0-9]/, '')
    def BUILD_ID = build_numb.findAll(/\d+/)
    echo "The build id from the string is ${BUILD_ID}"

Any help would be great.

Thanks Pritish


Solution

  • Using a simple regular expression will find the first number in the string. This code

    def build_numb = "ABC/MyABC/XYZ/POC-xyz-api-oci #89"
    
    def matcher = (build_numb =~ /\d+/)
    if (matcher) {
        def BUILD_ID = matcher[0]
        print "The build id from the string is ${BUILD_ID}"
    }
    

    will print:

    The build id from the string is 89