Groovy Tip: Accessing Pattern Matcher instance Used in Switch Case Statements

Groovy allows you to use regular expression patterns in the switch case statements

doMatch '2'
doMatch 'a1'
 
def doMatch(s) {
    switch(s) {
        case ~/\d/:
            println 'a digit'
            break
        case ~/.*\d/:
            println 'ends with a digit'
    }
}

But what if you needed access to the underlying matcher instance that was used to do the pattern matching. Is there any magic symbol (‘$’, ‘#’, ‘$$’, ‘##’, ….) that gives you handle to that matcher in Groovy?

The short answer is: No.

The longer answer is: Yes, and here is how you can do it:

import java.util.regex.Matcher
 
def s = 'tracking_level_9'
 
switch(s) {
    case ~/tracking_level_(\d)/:
        def m = Matcher.lastMatcher
        println m[0][1]
        assert '9' == m[0][1]
}

Hope it helps some time.

Advertisements