Groovy Regex: Capture group in Switch Statement

10,641

Solution 1

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]}"
}

Solution 2

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;
}
Share:
10,641
Reimeus
Author by

Reimeus

 

Updated on June 19, 2022

Comments

  • Reimeus
    Reimeus almost 2 years

    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?