正则表达式:如果后面有一组运算符,如何捕获括号组?

时间:2018-08-22 19:09:47

标签: python regex python-3.x parentheses

\(([^\\(\\)]+)\)

我上面的正则表达式捕获了表格各组括号之间的所有内容

(Hello OR there) AND (big AND wide AND world)

我知道

Hello OR there
big AND wide AND world

但是当方括号内的术语中带有括号时,它会下降

(Hello OR there AND messing(it)up) AND (big AND wide AND world)

返回

it
big AND wide AND world

我要

Hello OR there AND messing(it)up
big AND wide AND world

我不确定regex是否可行,或者最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用以下模式:

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

(?R)子表达式recurses the entire pattern if possible

您可以尝试here


输入:

(Hello OR there AND messing(it)up) AND (big AND wide AND world)

捕获的组是:

Group 1.    47-79   `Hello OR there AND messing(it)up`
Group 1.    86-108  `big AND wide AND world`

如果您使用的是Python,则可以使用regex模块:

import regex

mystring = '(Hello OR there AND messing(it)up) AND (big AND wide AND world)'
print(regex.findall('(?V1)\(((?:[^()]+|(?R))*+)\)',mystring))

打印:

['Hello OR there AND messing(it)up', 'big AND wide AND world']