Search code examples
regexjenkinsgroovyjenkins-pipeline

Branch specifier regex in Jenkins scripted pipeline


Suppose i want to define pipeline for different branches under same scripted pipeline, how to define the regex for certain pattern of branches. Say for example :-

if(env.BRANCH_NAME ==~ /release.*/){
	 stage("Deploy"){
		echo 'Deployed release to QA'
	 }

Here i want to define that regex in such a way for any branch of the pattern

*release*

(meaning any branch with release string in it). How to achieve that?

And similarly how to achieve something like :-

if the branch is anything but develop, master, release(pattern).


Solution

  • If you're using groovy you may use the following

    if ((env.BRANCH_NAME =~ '.*release.*').matches()) {
        stage("Deploy"){
            echo 'Deployed release to QA'
        }
    }
    

    And if you want to match any branch name but develop, master or release, you may use the following regex

    if ((env.BRANCH_NAME =~ '^((?!develop|master|release).)*$').matches()) {
        stage("Deploy"){
            echo 'Deployed release to QA'
        }
    }