我尝试过添加嵌套捕获组和带有位置信息的命名组。
你可以在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('');
});
});
架构
- 采用正则表达式模板并确定它将生成的捕获组。将其保存为一组组项和嵌套信息,以提供给扩展的 exec() 调用。
- 使用正则表达式查找捕获开始、非捕获元素、捕获名称和捕获结束。为可怕的 \( 和 \) 项目正确设置陷阱。
- 捕获项及其父项的非递归检查(使用引用计数)。
- 使用上面提取的捕获组信息运行 exec()。
- 使用子字符串函数为每个捕获组提取数据
- 为找到的每个结果将所有内容放入一个数组中,然后将数组发回。