我正在使用正则表达式模式来匹配嵌套括号的指数深度。虽然我有一个用于浅嵌套的工作解决方案,但当嵌套深度变得很深时,它就失败了。
下面是我当前的正则表达式模式:
const regex = /\(([^()]+)\)/;
const text = "(((A))) (((((B))))) (((((((C)))))))";
const matches = text.match(regex);
console.log(matches);
在这个例子中,我想匹配最深的括号内的最里面的内容,比如“C”。但是,我当前的正则表达式代码只匹配“A”和“B”。
我正在寻找一个正则表达式模式,它可以处理匹配嵌套在深括号中的最里面的内容,比如示例中的“C”。任何见解或更正我的正则表达式代码将不胜感激!
2条答案
按热度按时间c7rzv4ha1#
您忘记了全局修饰符
/g
您可以在捕获结果中避免括号,并通过一些查找来避免捕获组的需要:
根据输入的复杂性,您可能很容易遇到问题。例如,
D
而不是C
的期望是否匹配?哎呀...1mrurvl12#
似乎不可能使用1个正则表达式,但您可以匹配左括号+内容并检查右括号是否匹配: