Are there named groups in Groovy regex pattern matches?
This doesn't name the groups, but a closure does parameterise the match:
("John 19" =~ /(\w+) (\d+)/).each {match, name, age ->
println match
println name
println age
}
which outputs:
John 19
John
19
This is a useful reference: http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/
Assuming you are using on Java 7+, you can do:
def matcher = 'John 19' =~ /(?<name>\w+) (?<age>\d+)/
if( matcher.matches() ) {
println "Matches"
assert matcher.group( 'name' ) == 'John'
assert matcher.group( 'age' ) == '19'
}
else {
println "No Match"
}
If you are not on java 7 yet, you'd need a third party regex library