给定以下 Groovy 代码 switch 语句:
def vehicleSelection = "Car Selected: Toyota"
switch (vehicleSelection) {
case ~/Car Selected: (.*)/:
println "The car model selected is " + ??[0][1]
}
是否可以在不定义新 ( def
) 变量的情况下提取单词“Toyota” ?
这可以使用GroovylastMatcher
添加的方法:Matcher
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]}"
}
基于对我非常有帮助的 tim_yates 回答:
如果你想在你的代码中避免一堆“Matcher.lastMatcher”,你可以创建一个辅助函数来充当别名。
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;
}