Something like:
def match = "John 19" =~ /(&name&)\w+ (&age&\d+)/
def name = match.name
def age = match.age
Is there a groovy syntax that allows for something like this (instead of of the fictional &
operator I made up?
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
Groovy regular expressions have a ==~ operator which will determine if your string matches a given regular expression pattern.
A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.
=~ is Groovy syntax to match text against a regular expression.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With