Groovy string.matches regex question


(Arn B) #1

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


(Arn B) #2

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 = m.group(1) (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]


(www.rboyapps.com - Make your home your butler!) #3

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


(Arn B) #4

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
}


(www.rboyapps.com - Make your home your butler!) #5

Thanks.

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.


(Arn B) #6

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("[?&]")
   commands.each
	  { cmd ->

Perhaps by changing the mask from
(.*)[~]{2}([0-9]{3,5})
to
((.*)[~]{2}([0-9]{3,5}))+
it may find all the matches


(www.rboyapps.com - Make your home your butler!) #7

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.


(Arn B) #8

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.


(Arn B) #9

Two online regex testing sites. Unfortunately no Groovy, but Java and javascript
https://regex101.com/
https://www.freeformatter.com/java-regex-tester.html