Given the following Groovy code switch statement:
def vehicleSelection = "Car Selected: Toyota"
switch (vehicleSelection) {
case ~/Car Selected: (.*)/:
println "The car model selected is " + ??[0][1]
}
Is it possible to extract the word "Toyota" without defining a new (def
) variable?
This is possible using the lastMatcher
method added to Matcher
by Groovy:
import java.util.regex.Matcher
def vehicleSelection = 'Car Selected: Toyota'
switch( vehicleSelection ) {
case ~/Car Selected: (.*)/:
println "The car model selected is ${Matcher.lastMatcher[0][1]}"
}
Building on tim_yates answer that was really helpful for me:
If you want avoid a bunch of "Matcher.lastMatcher" in your code you can create a helper function to act as an alias.
import java.util.regex.Matcher
static Matcher getm()
{
Matcher.lastMatcher
}
def vehicleSelection = 'Car Selected: Toyota'
switch( vehicleSelection ) {
case ~/Car Selected: (.*)/:
println "The car model selected is ${m[0][1]}"
break;
}
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