Regular expression with Groovy

//regex patterns look strange, but groovy makes them look better
//use slashy syntax to declare a pattern, get rid of double-esacping
//example below both defines the same pattern to match a time like 15:01
assert "\\d\\d:\\d\\d" == /\d\d:\d\d/
 
//find a string, return true if found, false otherwise
assert 'The time is 15:01' =~ /\d\d:\d\d/
 
//note, you can easily use this for branching
def timeString = 'It is now 17:34'
def timeRegex = /\d\d:\d\d/
if (timeString =~ timeRegex) assert true
else assert false
 
//calling matcher.find() finds the first occurrence, then steps to the next if called again
//notice we used a regex group in the pattern: /(\d\d:\d\d)/
def matcher = ("It is 15:01, it is 15:02, it is 15:03" =~ /(\d\d:\d\d)/ )
assert matcher instanceof java.util.regex.Matcher
def times = []
while (matcher.find())
{
    times << matcher.group() //this adds each match to the list
}
assert times.size() == 3
assert times.join(",") == "15:01,15:02,15:03"
 
//a more groovy way to the same thing as above, eachMatch method in String
//note: no grouping parentheses needed in regex! /\d\d:\d\d/
times = []
"It is 15:01, it is 15:02, it is 15:03".eachMatch(/\d\d:\d\d/) {
    times << it[0] //it is a list, position 0 contains the complete match
}
assert times.size() == 3
assert times.join(",") == "15:01,15:02,15:03"
 
//using groups with the matcher and each closure. Within the pattern, we can use GString replacements to make
//the pattern readable
def DATE = /\d\d.\d\d.\d\d\d\d/
def TIME = /\d\d:\d\d/
def dates = []
("Today is 31.01.2007, 15:01. Tomorrow is 01.02.2007, 15:01" =~ /($DATE), ($TIME)/).each { all, date, time ->
    dates << date
}
assert dates.size() == 2
assert dates.join(', ') == '31.01.2007, 01.02.2007'