Home > Net >  Test if there is a match when using regular expression in jenkins pipeline
Test if there is a match when using regular expression in jenkins pipeline

Time:10-22

I am using regex to grab a number from a string in my pipeline it works ok as long that I have a match, but when there is no match I get an error

java.lang.IndexOutOfBoundsException: index is out of range 0..-1 (index = 0)

There error happens when i try to capture the group on following line

 env.ChangeNr = chngnr[0][1] 

How can i test if there isn't a match from my capture group ?

This is the pipeline

pipeline {
    agent {
        node {
            label 'myApplicationNode'
        }
    }
    environment {
        GIT_MESSAGE = "${bat(script: "git log --no-walk --format=format:%%s ${GIT_COMMIT}", returnStdout: true)}".readLines().drop(2).join(" ")
    }
    stages {
        stage('get_commit_msg'){              
            steps {
                script {
                     def gitmsg=env.GIT_MESSAGE
                     def chngnr = gitmsg =~/([0-9]{1,8})/
                     env.ChangeNr = chngnr[0][1] /* put test if nothing is extracted */                 
                }
            }
        }
    }
}

CodePudding user response:

In groovy when you use the =~ (find operator) it actually creates a java.util.regex.Matcher and therefore you can use any of its standard methods like find() or size(), so in your case you can jest use the size function to test if there are any matched patterns before you attempt to extract any groups:

def chngnr = gitmsg =~/([0-9]{1,8})/
assert chngnr.size() > 0 
env.ChangeNr = chngnr[0][1]

Another nice option is to use the =~ operator in context of boolean, in this case, Groovy implicitly invokes the matcher.find() method, which means that the expression evaluates to true if any part of the string matches the pattern:

def chngnr = gitmsg =~/([0-9]{1,8})/
if(chngnr){
    env.ChangeNr = chngnr[0][1]
}
else {
   ...
}

You can read more info on Groovy Regular Expressions Here

  • Related