Reading — step 1 of 5
Learn
~1 min readStrings, Regex, I/O
Groovy has regex literals, operators, and a smooth API on top of Java's regex.
Regex literals
def pattern = ~/\d+/ // pattern compiled at parse time
def alt = ~"\\d+" // alternative — escape backslashes
The ~/.../ syntax produces a java.util.regex.Pattern.
Match operators
"hello123" =~ /\d+/ // creates a Matcher
"hello123" ==~ /[a-z]+/ // exact match — boolean
"hello123" =~ /\d+/ ? "contains digits" : "no digits"
=~— find any match (returns Matcher)==~— exact full-string match (returns boolean)
Extracting captures
def m = "name: Ada, age: 36" =~ /name: (\w+), age: (\d+)/
if (m) {
def name = m[0][1] // first match, first capture group
def age = m[0][2]
println "$name is $age"
}
m[0] is the first match (whole match + groups). m[0][0] is the full match, m[0][1..n] are the groups.
Find all matches
def matcher = "phone 555-1234 fax 555-5678" =~ /\d{3}-\d{4}/
matcher.each { println it } // "555-1234", "555-5678"
// Or collect:
def numbers = ("phone 555-1234" =~ /\d+/).findAll()
// ["555", "1234"]
Replace
def s = "hello world"
s.replaceAll(/o/, "0") // "hell0 w0rld"
// With closure for dynamic replacement:
s.replaceAll(/\w+/) { match ->
match.toUpperCase()
}
// "HELLO WORLD"
Common patterns
// Email-ish
~/[\w.-]+@[\w.-]+/
// URL-ish
~/https?:\/\/[\w.-]+(\/.*)?/
// Date
~/\d{4}-\d{2}-\d{2}/
// Numbers
~/\d+/
~/\d+\.\d+/
Multi-line, case-insensitive, etc.
Use Java's flag syntax inside the pattern:
(?i)— case-insensitive(?s)— dot matches newlines(?m)— multiline (^ and $ per line)
"HELLO" ==~ /(?i)hello/ // true
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…