Regex for matching branch jenkins declarative pipeline

12,182

Solution 1

This worked for me.

isPatch = (env.BRANCH_NAME ==~ /Patch_For_*([a-z0-9]*)/)

Solution 2

The problem is with NOT operator.

'!=~' is not valid match operator for Groovy, and must be replaced. Rewritten form of IF NOT MATCH regex, should look like this:

isPatch = !(env.BRANCH_NAME =~ /Patch_For_*([a-z0-9]*)/)

So you see, NOT operator ! should go out of boolean match expression, which should be enclosed to parentheses and NOT put right before it.

Share:
12,182
smilyface
Author by

smilyface

Call me deeep. I am from India. Work as a Solution Architect in a leading software company. I am much interested in programming and testing / (of course) criticising programs / applications done by my friends or colleagues. More enthusiastic to learn / read new techy news.

Updated on June 08, 2022

Comments

  • smilyface
    smilyface almost 2 years

    I have a requirement to allow patch branch too with master branch (we use git).

    stages {
        stage('PR Build') {
            when {
                beforeAgent true
                expression {
                            isMaster = env.BRANCH_NAME == masterBranchName
                            isPatch = env.BRANCH_NAME !=~ /Patch_For_*([a-z0-9]*)/
                            echo "isMaster : ${isMaster} , isPatch : ${isPatch}"
                            return !isMaster && !isPatch
                           }
            }
            steps {
                script{
                    buildType = 'PR'
                }
                // Do PR build here...
            }
        }
    
        stage('Build master / patch branch') {
            when {
                beforeAgent true
                expression {
                            isMaster = env.BRANCH_NAME == masterBranchName
                            isPatch = env.BRANCH_NAME !=~ /Patch_For_*([a-z0-9]*)/
                            echo "isMaster : ${isMaster} , isPatch : ${isPatch}"
                            return isMaster || isPatch
                           }
            }
            steps {
                script {
                    buildType = 'deployment'
                    )
                }
                // Do master or patch branch build and deployment
            }
        }
    

    Here the issue is in regex part of Patch branch. I want jenkins to check whether the patch branch is starting with Patch_For_shortCommitIDSha for example Patch_For_87eff88

    But the regex I wrote wrongly allows branches other than branches starting with Patch_For_