How to match and return a single substring?

117 views
Skip to first unread message

Ricardo Fernández Serrata

unread,
Jul 25, 2021, 9:37:00 PM7/25/21
to Automate
How matches() can be set to do this? I tried wildcards (".*" and ".+") look-arounds (look-behind and look-ahead) and prefix flags, and they all work with findAll, but not matches(). matches() only tries to match the whole text string, while findAll() can match substrings. I am forced to use findAll(text, regex)[0] for the 1st match and findAll(text, regex)[-1] for the last match. I know how to use indexOf along with substr or slice to to the same with string literals, but sometimes I need to use a regex with meta-character interpretation.

Please help. If there's no way, then I would really like a function to do it.

By the way. I would also like a lastIndexOf() function, using split(text0, text1)[-1] or substr(text0, -indexOf(reverse(text0), text1)) shouldn't be necessary for simple things that don't require regex. A dedicated function would be more efficient and easier to use

Shari Shark

unread,
Jul 25, 2021, 9:50:29 PM7/25/21
to automa...@googlegroups.com
Simply use a capturing group and select the second element of the return array.

Example: put this into a variable set block to test it out. 

matches("this is a test string, looking for text.", ".*?(te.t).*")[1]


Note the question mark. With the question mark, the result is test. Without the question mark, the result is text. 

Also note this this will return null is there's no matching element.

--
You received this message because you are subscribed to the Google Groups "Automate" group.
To unsubscribe from this group and stop receiving emails from it, send an email to automate-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/automate-user/5d4cf060-2cb6-4856-b4f8-7caec066d9dfn%40googlegroups.com.

Ricardo Fernández Serrata

unread,
Jul 25, 2021, 10:46:52 PM7/25/21
to Automate
Thanks! I didn't know capturing groups could be used like this
Reply all
Reply to author
Forward
0 new messages