Using Regular Expression to Capture Multiple Matches and put inside Multiple Variables

Hi guys, I am trying to get the matches and put it inside in the variables using a regular expression in KM.
But the problem is, it will turn KM not responding when I tried my code there.

Because in the docs text I want to get up to 30 matches so in my long code I need to input the code repetitive 30 times but KM will not respond or load for so long that I need to force close the application.
But in my link below the long code shows only 8 repetitive, to demonstrate what I want.

Here is my simple code.
Regex 1st Attempt

The long code
Long Code 2nd Attempt

Set Variable to Text.kmmacros (108.0 KB)

If anyone has a better solution for this or edit my Regex code to have the option on how many variables to open or to shorten my code that can save up to 70 matches. so from Variable m1 - Variable m70

In this case, what you want is the For Each action looking for a single instance of your regex. While I suspect that your ultimate goal for this task doesn't really require each match being saved into separate variables, for the purposes of this question, here's how For Each can be used to capture each match into a dynamically named variable (Test1, Test2 in this case, but you can of course use m or whatever you want):

Set Variable to Text 1.1.kmmacros (109.3 KB)


1st Match
Final 12th Match

1 Like

Thank you very much, it works like magic, :slight_smile: I tried solving this looking for answers on the internet but no success. Thank you again.

1 Like

Hi, I have an approach to the problem that uses JavaScript and is very fast in operation.

There are two macros that I have written: the first returns all the multiple matches plus capture groups (if any are specified in the regex). The second macro is slightly different in that it returns only the capture groups. Both macros return an array that contains the matches plus variables that indicate the number of matches. Refer to comment at the start of each macro for usage information. Both macros avoid the need for a KM looping structure.

While I don't pretend to be either a JavaScript nor KM expert, I use these macros daily very successfully to extract information from both web (HTML) pages and text documents. I hope you can find a use for them.

These may be of use to you

Here they are:

The first macro libGetAllMatches.kmmacros (7.4 KB)

The second macro libGetAllCaptureGroups.kmmacros (7.8 KB)

1 Like

Thank you I can use this also :smiley:

1 Like