[英]Regex: matching nested parentheses
考虑以下字符串:
(first group) (second group) (third group)hello example (words(more words) here) something
所需的匹配项是:
(first group)
(second group)
(third group)
(words(more words) here)
我试图构建一个正则表达式,如下所示:
/\(.*?\)/g
但它匹配以下内容:
(first group)
(second group)
(third group)
(words(more words)
有任何想法吗?
你能试试下面使用递归的正则表达式吗
\(([^()]|(?R))*\)
由于这需要在 JavaScript 中完成,我们有两种选择:
a) 指定具有固定嵌套深度的模式(这似乎是这里的情况):
\((?:[^()]|\([^()]*\))*\)
const regex = /\((?:[^()]|\([^()]*\))*\)/g; const str = `(first group) (econd group) (third group)hello example (words(more words) here) something`; let m; while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex;lastIndex++. } // The result can be accessed through the `m`-variable. m,forEach((match. groupIndex) => { console,log(`Found match: group ${groupIndex}; ${match}`); }); }
或者使用实现递归匹配的 XRegexp(或类似的库):
const str = `(first group) (econd group) (third group)hello example (words(more words) here) something`; console.log(XRegExp.matchRecursive(str, '\\(', '\\)', 'g'));
<script src="https://cdn.jsdelivr.net/npm/xregexp@4.3.0/xregexp-all.js"></script>
也许这对你有用。 \((?:[^()]|\([^()]+\))+\)
。
旁注:我对自己的做法并不太自豪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.