MACRO: Get List of RegEx Capture Group of Multiple Matches

I have no words to describe to you how grateful I am for this post. I managed to stumble across it (eventually), and it showed me how to solve almost all the issues I was having. A little Googling and I solved everything else.

I’m sitting here around 3am, which should tell you something already about how much this has been festering in my brain.

The getMatches() function was a godsend, because I could not get non-capturing groups, or lookbehinds, to work.

Here’s what I ended up using for my purposes (slightly edited), thanks to you and Google:

function run() {
'use strict';

var _kme = Application("Keyboard Maestro Engine");
var _prefix = _kme.getvariable("thePrefix");
var _string = _kme.getvariable("theSource");

var _re = new RegExp("([>%])(" + _prefix + "[^<%>=+-/\.&]*)", "gm");

var _matches = getMatches(_string, _re, 2).filter(onlyUnique).sort().join("\n");

return _matches;

function getMatches(string, regex, groupIndex) {
  var _matches = [];
  var _match;
  while (_match = regex.exec(string)) {
    _matches.push(_match[groupIndex].trim());
  }
  return _matches;
}

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}
}

Again, seriously undying gratitude!

1 Like