考虑以下字符串:
(first group) (second group) (third group)hello example (words(more words) here) something
想要的匹配是:
(first group)
(second group)
(third group)
(words(more words) here)
我尝试构建如下regex:
/(.*?)/g
但它与以下内容相匹配:
(first group)
(second group)
(third group)
(words(more words)
有什么想法吗?
由于这需要在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>
也许这对您的情况有效。CCD_ 1。
旁注:我对自己的表现并不感到骄傲。
你能试试下面使用递归的正则表达式吗
(([^()]|(?R))*)