Regex挑战:匹配具有指数深度的嵌套括号

uplii1fm  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(91)

我正在使用正则表达式模式来匹配嵌套括号的指数深度。虽然我有一个用于浅嵌套的工作解决方案,但当嵌套深度变得很深时,它就失败了。
下面是我当前的正则表达式模式:

const regex = /\(([^()]+)\)/;
const text = "(((A))) (((((B))))) (((((((C)))))))";

const matches = text.match(regex);
console.log(matches);

在这个例子中,我想匹配最深的括号内的最里面的内容,比如“C”。但是,我当前的正则表达式代码只匹配“A”和“B”。
我正在寻找一个正则表达式模式,它可以处理匹配嵌套在深括号中的最里面的内容,比如示例中的“C”。任何见解或更正我的正则表达式代码将不胜感激!

c7rzv4ha

c7rzv4ha1#

您忘记了全局修饰符/g

const regex = /\(([^()]+)\)/g;
const text = "(((A))) (((((B))))) (((((((C)))))))";

const matches = text.match(regex);
console.log(matches);

您可以在捕获结果中避免括号,并通过一些查找来避免捕获组的需要:

const regex = /(?<=\()[^()]+(?=\))/g;
const text = "(((A))) (((((B))))) (((((((C)))))))";

const matches = text.match(regex);
console.log(matches);

根据输入的复杂性,您可能很容易遇到问题。例如,D而不是C的期望是否匹配?哎呀...

const regex = /(?<=\()[^()]+(?=\))/g;
const text = "(((A))) (((((B))))) (((((((C))(((((D))))))))))";

const matches = text.match(regex);
console.log(matches);
1mrurvl1

1mrurvl12#

似乎不可能使用1个正则表达式,但您可以匹配左括号+内容并检查右括号是否匹配:

const text = "(((A))) (((((B))))) (((((((C))))))) ((((bad parentheses))((good ones))";

// captures opening parentheses + content
const regex = /(\(+)([^\)]+)/g;
const result = [];

let me;
while(m = regex.exec(text)){
  // check whether closing parentheses match
  const from = m.index + m[0].length;
  const closing = text.slice(from, from + m[1].length + 1);
  new RegExp('^\\){' + m[1].length + '}($|[^)])').test(closing) && result.push(m[2]);
}

console.log('captures:', ...result.map(JSON.stringify));

相关问题