匹配平衡括号的正则表达式

2024-03-29 06:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个正则表达式来选择两个外括号之间的所有文本。

示例:some text(text here(possible text)text(possible text(more text)))end text

结果:(text here(possible text)text(possible text(more text)))


Tags: text文本示例heremoresome括号end
3条回答

我想加上这个答案作为快速参考。随时更新。


.NET Regex使用balancing groups

\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\)

其中c用作深度计数器。

Demo at Regexstorm.com


PCRE使用recursive pattern

\((?:[^)(]+|(?R))*+\)

Demo at regex101;或无替换:

\((?:[^)(]*(?R)?)*+\)

Demo at regex101;或unrolled用于性能:

\([^)(]*+(?:(?R)[^)(]*)*+\)

Demo at regex101;模式粘贴在代表(?0)(?R)处。

Perl、PHP、记事本++、Rperl=TRUEPythonRegex package(?V1)用于Perl行为。


Ruby使用subexpression calls

使用Ruby 2.0 \g<0>可以调用完整模式。

\((?>[^)(]+|\g<0>)*\)

Demo at Rubular;Ruby 1.9只支持capturing group recursion

(\((?>[^)(]+|\g<1>)*\))

Demo at Rubular(自Ruby 1.9.3以来的atomic grouping


JavaScriptAPI :: XRegExp.matchRecursive

XRegExp.matchRecursive(str, '\\(', '\\)', 'g');

JS、Java和其他regex风格,无递归,多达2级嵌套:

\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)

Demo at regex101。深入nesting needs to be added到模式。
在不平衡的括号中更快地失败drop the ^{} quantifier.


Java:一个有趣的idea using forward references by @jaytea


Reference - What does this regex mean?

您可以使用regex recursion

\(([^()]|(?R))*\)

正则表达式是错误的工具,因为您正在处理嵌套结构,即递归。

但是有一个简单的算法可以做到这一点,我将in this answer描述为previous question

相关问题 更多 >