Search code examples
regexjenkinsjenkins-pipelinedeclarative

Regex for matching branch jenkins declarative pipeline


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_


Solution

  • This worked for me.

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