Groovy string.matches regex question

How do I test the capture groups in the following regex matches code example:

def string = “Xfinify 3400-X Keypad"
if (string.matches(”(.*)(?i)keypad(.*)")){
// the result is true but want to examine capture group 0 ("Xfinify 3400-X Keypad ), 1(Xfinify 3400-X), 2(null) here, for example
if (something??? [1] == “yada yada…”)

What is something???

Thank you

Found a rather arcane Groovy regex construct, I’m used to a simple PHP preg_match, that should work but does not. All other attempts at directly using Matcher also fail. Anyone know how to do this in SmartThings Groovy?

Test code
def txt = "xfinity 3400 Keypad xyz"
def m
if ((m = txt =~ /(.)(?i)(keypad)(.)/)) {
log.debug “m $m”
def match = (this would be line 176 noted below)
log.debug “MATCH=$match”}

Error log
9:49:16 AM: error java.lang.SecurityException: Getting properties on class java.util.regex.Matcher is not allowed @ line 176
9:49:16 AM: debug m java.util.regex.Matcher[pattern=(.)(?i)(keypad)(.) region=0,23 lastmatch=xfinity 3400 Keypad xyz]

@slagle how does one get access to the regex groups after the matcher completes?

Sample of some code I use

def cmd =data~~1000
def mask = /(.*)[~]{2}([0-9]{3,5})/
if((matcher = cmd =~ mask))
log.debug "Matched ${it}"
log.debug "${matcher[0]}"
log.debug “${matcher[0][1]}” //the command
log.debug “${matcher[0][2]}” //the delay

1 Like


Unfortunately I’m dealing with an indeterminate set of data so I had to resort to try catch with an iteration. Very messy but the only way I can see if you don’t know how many groups are being matched.

If I understand your response, you wanted something on the order of PHP PREG_MATCH_ALL vs a simple PREG_MATCH. Unfortunately I also had to code around that issue.

   def commands = phrase.split("[?&]")
	  { cmd ->

Perhaps by changing the mask from
it may find all the matches

1 Like

I did try that earlier but it didn’t seem to work, maybe I’ve got my regex wrong, instead of capturing stuff between the beginning and end pattern markers it ends up capturing the beginning and end pattern markers themselves multiple times.

Perhaps the pattern is missing the capture parens for the group?

I also bumped into many very annoying PHP vs Groovy regex pattern variations. It was a real PITA getting functional Groovy regex match code.

Also, if I remember correctly, attempting to use the Java Matcher class fails in ST Groovy.

If you post or PM your pattern and sample data, I will take a look at it.

Two online regex testing sites. Unfortunately no Groovy, but Java and javascript

1 Like