实例的正则表达式匹配总数

The*_*978 7 javascript regex

我的测试字符串包含一个方括号和一个闭合方括号的4个实例,因此我希望以下正则表达式返回4个匹配项,但只返回1个匹配项。

const test = "sf[[[[asdf]]]]asdf"
const regExp = new RegExp(/^.*\[.*\].*$/, "g");
const matches = test.match(regExp).length;

console.log(matches);
Run Code Online (Sandbox Code Playgroud)

Kev*_*Bot 8

您可以结合使用递归和正则表达式:

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'));
Run Code Online (Sandbox Code Playgroud)