Regular Expressions
def text = "Order 123 shipped on 2025-10-24, order 456 pending"
// Pattern operator ~
def pattern = ~/\d{4}-\d{2}-\d{2}/
println pattern.class // java.util.regex.Pattern
// Find operator =~ (Matcher)
def m = text =~ /order (\d+)/
println m.find(), m.size()
(text =~ /(\d+)/).each { match, num -> println num }
def all = (text =~ /\d+/).collect { it } // all matches
println text.findAll(/\d+/) // shortcut
println text.find(/\d{4}-\d{2}-\d{2}/)
// Match operator ==~ (the entire string must match)
println "2025-10-24" ==~ /\d{4}-\d{2}-\d{2}/ // true
println "abc123" ==~ /[a-z]+/ // false
// Groups
def date = "2025-10-24" =~ /(\d{4})-(\d{2})-(\d{2})/
if (date) {
def (full, year, month, day) = date[0]
println "$day/$month/$year"
}
def named = "John Smith" =~ /(?<first>\w+) (?<last>\w+)/
if (named.matches()) println named.group('last')
// Replace
println "hello world".replaceAll(/o/, "0")
println "john smith".replaceAll(/\b(\w)/) { full, ch -> ch.toUpperCase() }
println "a1b2c3".replaceAll(~/\d/) { (it as int) * 2 }
// In switch and grep
switch ("abc123") { case ~/^[a-
…