2024-03-29 06:52:57 发布
网友
我需要一个正则表达式来选择两个外括号之间的所有文本。
示例:some text(text here(possible text)text(possible text(more text)))end text
some text(text here(possible text)text(possible text(more text)))end text
结果:(text here(possible text)text(possible text(more text)))
(text here(possible text)text(possible text(more text)))
我想加上这个答案作为快速参考。随时更新。
.NET Regex使用balancing groups。
\((?>\((?<c>)|[^()]+|\)(?<-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)处。
(?0)
(?R)
Perl、PHP、记事本++、R:perl=TRUE、Python:Regex package和(?V1)用于Perl行为。
(?V1)
Ruby使用subexpression calls。
使用Ruby 2.0 \g<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。
我想加上这个答案作为快速参考。随时更新。
.NET Regex使用balancing groups。
其中
c
用作深度计数器。Demo at Regexstorm.com
PCRE使用recursive pattern。
Demo at regex101;或无替换:
Demo at regex101;或unrolled用于性能:
Demo at regex101;模式粘贴在代表
(?0)
的(?R)
处。Perl、PHP、记事本++、R:perl=TRUE、Python:Regex package和
(?V1)
用于Perl行为。Ruby使用subexpression calls。
使用Ruby 2.0
\g<0>
可以调用完整模式。Demo at Rubular;Ruby 1.9只支持capturing group recursion:
Demo at Rubular(自Ruby 1.9.3以来的atomic grouping)
JavaScriptAPI :: XRegExp.matchRecursive
JS、Java和其他regex风格,无递归,多达2级嵌套:
Demo at regex101。深入nesting needs to be added到模式。} quantifier.
在不平衡的括号中更快地失败drop the ^{
Java:一个有趣的idea using forward references by @jaytea。
Reference - What does this regex mean?
您可以使用regex recursion:
正则表达式是错误的工具,因为您正在处理嵌套结构,即递归。
但是有一个简单的算法可以做到这一点,我将in this answer描述为previous question。
相关问题 更多 >
编程相关推荐