I have played around with adding nested capture groups and named groups with position information.
You can play with some regex on jsfiddle...
https://jsfiddle.net/smuchow1962/z5dj9gL0/
/*
Copyright (c) 2019 Steven A Muchow
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Enhanced RegEx JS processing
Adds position information for capture groups (nested ones too) AND named group items.
*/
class RegexContainer {
static _findCaptureGroupsInRegexTemplate(re, input) {
let refCount = 0; let matches = []; let res; let data;
re.lastIndex = 0;
while ((res = re.exec(input)) !== null) {
if (isCapturingStartItem(res[0])) {
refCount++;
data = {parent: 0, refCount: refCount, start: res.index};
if (res.groups.name) { data.name = res.groups.name; }
matches.push(data);
} else if (input.charAt(res.index) === ')') {
let idx = matches.length;
while (idx--) {
if (matches[idx].end === undefined) {
matches[idx].end = re.lastIndex;
matches[idx].source = input.substring(matches[idx].start, matches[idx].end);
break;
}
}
refCount--;
let writeIdx = idx;
while (idx--) {
if (matches[idx].refCount === refCount) {
matches[writeIdx].parent = idx + 1;
break;
}
}
}
}
matches.unshift({start: 0, end: input.length, source: input});
return matches;
function isCapturingStartItem(str) {
if (str !== '(') { return (str.search(/\(\?<\w/)!==-1); }
return true;
}
}
static execFull(re, input, foundCaptureItems) {
let result; let foundIdx; let groupName; const matches = [];
while ((result = re.exec(input)) !== null) {
let array = createCustomResultArray(result);
array.forEach((match, idx) => {
if (!idx) {
match.startPos = match.endPos = result.index;
match.endPos += result[0].length;
delete match.parent;
return;
}
let parentStr = array[match.parent].data;
foundIdx = (match.parent < idx - 1) ? parentStr.lastIndexOf(match.data) : parentStr.indexOf(match.data);
match.startPos = match.endPos = foundIdx + array[match.parent].startPos;
match.endPos += match.data.length;
if ((groupName = foundCaptureItems[idx].name)) { match.groupName = groupName; }
});
matches.push(array);
if (re.lastIndex === 0) { break; }
}
return matches;
function createCustomResultArray(result) {
let captureVar = 0;
return Array.from(result, (data) => {
return {data: data || '', parent: foundCaptureItems[captureVar++].parent,};
});
}
}
static mapCaptureAndNameGroups(inputRegexSourceString) {
let REGEX_CAPTURE_GROUPS_ANALYZER = /((((?<!\\)|^)\((\?((<(?<name>\w+)))|(\?<=.*?\))|(\?<!.*?\))|(\?!.*?\))|(\?=.*?\)))?)|((?<!\\)\)(([*+?](\?)?))?|({\d+(,)?(\d+)?})))/gm;
return RegexContainer._findCaptureGroupsInRegexTemplate(REGEX_CAPTURE_GROUPS_ANALYZER, inputRegexSourceString);
}
static exec(re, input) {
let foundCaptureItems = RegexContainer.mapCaptureAndNameGroups(re.source);
let res = RegexContainer.execFull(re, input, foundCaptureItems);
return {captureItems: foundCaptureItems, results: res};
}
}
let answers = [];
let regex = [
{ re: "[ \\t]*?\\[\\[(?<inner>\\s*(?<core>\\w(.|\\s)*?)\\s*?)]]", label: "NESTED Regex"},
{ re: "(?<context>((\\w)(\\w|-)*))((?<separator>( - ))?(?<type>(-|\\w)+)?\\s*(?<opt>(\\{.*}))?)?[\\t ]*", label: "simpler regex" },
]
let input = "[[ context1 ]] [[ context2 - with-style { andOpts : {data: 'some info'} } ]]";
regex.forEach( (item) => {
let re = new RegExp(item.re, 'gm');
let result = RegexContainer.exec(re,input);
result.label = item.label;
answers.push(result);
});
answers.forEach((answer,index) => {
console.log('==========================================================');
console.log('==== Item ' + index + ' label: ' + answer.label + ' regex: ' + answer.captureItems[0].source );
console.log('==========================================================\n\n');
let scannedItems = answer.results;
scannedItems.forEach( (match) => {
let full = match[0];
let mstr = full.data;
let substr = input.substring(full.startPos, full.endPos);
if (mstr !== substr) {
console.log('error in the parsing if you get here');
return;
}
console.log('==== Checking ' + mstr);
for (let i=1; i<match.length; i++) {
let capture = match[i];
if (capture.groupName) {
console.log(' ' + capture.groupName + ': ' + "```" + input.substring(capture.startPos,capture.endPos) + "```");
}
}
console.log('');
});
});
Architecture
- Take Regex Template and identify the capture groups it will generate. Save it off as an array of group items and nesting info to feed into the expanded exec() call.
- use regex to find capturing starts, non-capturing elements, capture names and capture endings. Trap properly for the dreaded \( and \) items.
- non-recursive inspection of capture items and their parents (using reference counting).
- run the exec() with the capture group information pulled above.
- use substring functions to extract data for each capture group
- put everything into an array for each result found and send the array back.