29

给定以下 Groovy 代码 switch 语句:

def vehicleSelection = "Car Selected: Toyota"

switch (vehicleSelection) {
   case ~/Car Selected: (.*)/:

      println "The car model selected is "  + ??[0][1] 
}

是否可以在不定义新 ( def) 变量的情况下提取单词“Toyota” ?

4

2 回答 2

40

这可以使用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]}"
}
于 2012-10-17T15:17:28.763 回答
7

基于对我非常有帮助的 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;
}
于 2013-12-15T03:14:48.357 回答