Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Regex: Capture group in Switch Statement

Tags:

regex

groovy

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?

like image 234
Reimeus Avatar asked Oct 17 '12 15:10

Reimeus


2 Answers

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]}"
}
like image 114
tim_yates Avatar answered Nov 05 '22 08:11

tim_yates


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;
}
like image 21
Kurgen Avatar answered Nov 05 '22 08:11

Kurgen