Saturday 8 October 2016

Groovy Regular Expressions

A simple example to separate letter and numbers. In this case I have an environment variable which I want to separate into designation (UAT) and number (05)

def env = "UAT05"

def result  = env =~ /(\w*?)(\d+)/

def envName = result[0][1]
def envNumber = result[0][2]

println "ENV NAME: " + envName
println "ENV NUMBER: " + envNumber

The output is ...
ENV NAME: UAT
ENV NUMBER: 05

Notice the question mark in the regex  (\w*?) ... this means non-greedy 

If not used the result would have been ...
ENV NAME: UAT0
ENV NUMBER: 5

Things will make more sense if you take a look at element zero of result...
println "RESULT " + result[0]

The output is ...
RESULT : [UAT05, UAT, 05]



No comments:

Post a Comment