Doron Shai
Doron Shai

Reputation: 698

groovy if statement with regex in variable

I want to delete list of Jenkins jobs that begins with AAA (for example)

When i do it with explicit string it works fine

if (item.name ==~ /AAA.*/){  
    item.delete()
 }

but when i try to get the regex from a Jenkins Build property, i fail and the if is not called...

import hudson.model.*
import hudson.node_monitors.*
import hudson.slaves.*
import java.util.concurrent.*

jenkins = Hudson.instance

def thr = Thread.currentThread()

def build = thr?.executable

String REGEX = build.environment.get("Include_Regex")

println "REGEX is " + REGEX

for (item in jenkins.items){
   println("\t ${item.name}");
   println("\t ${item.name.getClass()}");
   if (item.name ==~ REGEX){  
       item.delete()
       println("TEST");
    }

} 

When I run it, i get a list of all jobs: Building in workspace /var/lib/jenkins/jobs/Bulk_Delete_Job/workspace

REGEX is /AAA.*/
     AAA_test_1
     class java.lang.String
     AAA_test_2
     class java.lang.String
     AAA_test_3
     class java.lang.String
     Bulk_Delete_Job
     class java.lang.String
     ConfiguredJob
     class java.lang.String
     JobZ
     class java.lang.String
     TEST_SCM
     class java.lang.String

But nothing is deleted / no "TEST" is printed -> the if is never true....

Assistance is required, Thanks!

Upvotes: 5

Views: 13356

Answers (1)

wolfs42
wolfs42

Reputation: 816

The String should not include the slashes - use AAA.* instead of /AAA.*/.

Upvotes: 7

Related Questions