MACRO: Get List of RegEx Capture Group of Multiple Matches
DOWNLOAD:
[JS] Get List of JavaScript Functions in Selection.kmmacros (33 KB)
I wrote this macro to extract a list of functions from a JXA/JavaScript script library, but it serves as a good example in general of how to process multiple RegEx matches, get the same Capture Group from each match.
The macro is setup to use either KM built-in Actions, or a custom JXA script.
It was not obvious to me how to use KM Actions at first, but with some great help from Peter (@peternlewis), I was able to design this macro.
If you want to Get List of RegEx Capture Group of Multiple Matches, then here is the key:
- Use the "For Each" Action to get each match into a variable
- Then use a "Search Variable" Action to get the Capture Group for that match
Both Actions can use the same RegEx pattern.
VER: 1.1 Last Update: Tue, Feb 16, 2016
Author: @JMichaelTX
PURPOSE: Extract a list of functions from Selection, Put on Clipboard
HOW TO USE:
(1) Select the text that contains the actual functions (like a Script Library file)
(2) Run this macro
NOTE: Macro is Setup in Demo Mode
You will need to enable/disable certain Actions for production use.
See the Comments in the macro for details.
JXA Script (initially disabled)
function run() {
'use strict';
var app = Application.currentApplication()
app.includeStandardAdditions = true
var myString = app.theClipboard();
var myRegEx = /^\s*?(function[ ]?\w*\(.*\)).*[\n\r]/gm;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
var matchesStr = matches.join("\n");
return (matchesStr)
//~~~~~~~~~~ END OF MAIN SCRIPT ~~~~~~~~~~~~~~~~~~
function getMatches(string, regex, groupIndex) {
groupIndex || (groupIndex = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[groupIndex]);
}
return matches;
} // END function getMatches
} // END function run