How Can I Do a Replace for EACH RegEx Match Found, as it is Found?

###How Can I Do a Replace for EACH RegEx Match Found, as it is Found?

###Use Case

  • I have a string with a number of substrings that have the same pattern
  • I need replace each occurrence (match) with an individual result, which requires a formula and/or a function (or multiple KM Actions to calculate the replacement)
  • Examples:
    • Replace all dates in one format with another format
    • Increment a seq# at the end of a string
  • For a real example, see this KM Topic: Replacing Substrings in Clipboard or Variable.

###JavaScript Solution
This is easily done in JavaScript

var sourceData = `
test1 on line 1
line that should not match 2
test25 on line 3
another line no match 4
test3 on line 5
another no match 6
`
var reTestNum = /^(test)(\d+)/gm;

//--- ADD 10 TO Number AFTER 'test' ---
var updatedData = sourceData.replace(reTestNum, function ($0, $1, $2) {
  var num = parseInt($2, 10) + 10;
  return $1 + num;
  });
  
  console.log(updatedData);
  
  //--- RESULTS  ---
  
  /* 
test11 on line 1
line that should not match 2
test35 on line 3
another line no match 4
test13 on line 5
another no match 6
 */

But I have been unable to design a KM solution that does not use a script.

Any ideas?

What I need is a way to update the source string for each match that is found in a KM For Each action (KM Wiki):

###This is What I'd Like to To Do
but is NOT currently supported.

Is there another way to accomplish this?

You can do a two-step regex:

[test] Replace Match with Calculation.kmmacros (5.5 KB)

Thanks, Tom.

I had thought about that approach but wasn't sure how to just update each match. Building a new string with all data solves that issue.

Still, it feels more like a workaround than a true solution. It takes a lot more steps than the JavaScript solution.

I think until/if @peternlewis gives us the capability to do a direct replacement as I showed in my proposed new Action, I'll just use JavaScript. When I have time, maybe I'll try to build a more general purpose solution using source data and regex pattern from KM variables.

There is no particularly good way to do this in Keyboard Maestro.

It is essentially the equivalent of the /e switch in Perl regex, or using a function in JavaScript or whatever. That is, search and replace where the result is calculated.

Keyboard Maestro does not have this facility. Yet. Anywhere except on my Mac anyway.

3 Likes

In lieu of Discourse providing Slack-style reaction-moji, let me just say: :open_mouth:

I look forward to rewriting my Japanese date converter macro that inspired this topic once this facility becomes available on all Macs running the latest KM :smile:

1 Like

Done, and I have to say, I think it turned out nicely: Tips: Show Examples of How KM8's New Features Have Improved Your Macros/Workflow - #3 by gglick?

1 Like

As noted, this is done in Keyboard Maestro 8.