我的测试字符串包含4个开放方括号的实例和一个封闭的方括号,因此我希望以下正则表达式返回4个匹配项,但它仅返回1。
const test = "sf[[[[asdf]]]]asdf"
const regExp = new RegExp(/^.*[.*].*$/, "g");
const matches = test.match(regExp).length;
console.log(matches);
您可以使用递归和正则表达式的组合:
function parse(str) {
const matches = [];
str.replace(/[(.*)]/, (match, capture) => {
matches.push(match, ...parse(capture));
});
return matches;
}
console.log(parse('sf[[[[asdf]]]]asdf'));
console.log(parse('st[[as[[asdf]]]a]sdf'));