我正在尝试创建一个JS正则表达式,它将找到未被引号括起的最里面的括号。括号可以无限嵌套。
示例1:
(This should not match (This will match "(with this)" intact), but will exclude this and (this))
因此,在示例中,结果将是This will match "(with this)" intact
示例2:
(This should not match (This will match with this intact), but will exclude this and (this))
因此,在示例中,结果将是This will match with this intact
我试过/\(([^\(\)]+)\)/
给了我最里面的括号,但是没有逃脱引号。
答案 0 :(得分:2)
如果你不介意自己剥掉外括号
/\([^()"]*(?:"[^"]*"[^()"]*)*\)/
在第一个示例输入中给出(This will match "(with this)" intact)
,在第二个示例中给出(This will match with this intact)
。
答案 1 :(得分:2)
这是一个可能的选择:
/\(((?:"\(|\)"|[^()])+)\)/
用法示例:
'( (a"(b)") )'.match(/\(((?:"\(|\)"|[^()])+)\)/) // ["(a"(b)")", "a"(b)""]
描述:
"\(|\)"|[^()] "( or )" or any char except parenthesis
((?:...)+) one or more times (capture -> group 1)
\(...\) enclosed in a pair of parenthesis