13

I am trying to detect the branch pattern on a when statement inside a stage.

Like this:

stage('deploy to staging') {
agent label:'some-node'
when { branch "feature/*" }
steps {
    sh './deploy_pr.sh'
}

}

What if I want a more complicated pattern?

I am trying to detect something like feature/0.10.25 and the following pattern doesn't work:

when { branch 'feature/[0-9]+.[0-9]+.[0-9]+' }

Doesn't work . And it's a correct regexp, according to https://regexr.com/

c4sh
  • 701
  • 1
  • 8
  • 22

1 Answers1

13

Ok ! So, through the error stack trace I found out that on the when-branch option, Jenkins compares with Ant style patterns: https://ant.apache.org/manual/dirtasks.html

That means it doesn't expect regexp, but simpler stuff like:

        */staging/*

I solved this by using the when-expression option instead, like this:

        when { 
            expression { BRANCH_NAME ==~ /feature\/[0-9]+\.[0-9]+\.[0-9]+/ }
        }

That uses groovy expressions as described here:

https://www.regular-expressions.info/groovy.html

Especially, look for the explanation of the ==~ operator, that was helpful.

For the regular expression itself, you can test yours here:

https://regexr.com/

c4sh
  • 701
  • 1
  • 8
  • 22
  • 1
    can use `\d` instead of `[0-9]`, i.e.: `BRANCH_NAME ==~ /feature\/\d+\.\d+\.\d+/` – leo4jc Oct 08 '19 at 20:27
  • Wanted to say that in this case, `BRANCH_NAME` directly corresponds to an environment variable that's set in your Jenkins pipeline. For me, `BRANCH_NAME` didn't exist, but `GIT_BRANCH` did. – Mani Nov 17 '20 at 09:43
  • @Mani I think it depends on you using multibranch pipeline (BRANCH_NAME), like I did, or a normal pipeline (GIT_BRANCH). https://stackoverflow.com/questions/42383273/get-git-branch-name-in-jenkins-pipeline-jenkinsfile – c4sh Nov 19 '20 at 14:21