\(([^\\(\\)]+)\)
我上面的正则表达式捕获了表单每组括号之间的所有内容
(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
我不确定正则表达式是否可以做到这一点,或者最好的方法是什么?
最佳答案
您可以使用以下模式:
\(((?:[^()]+|(?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']
关于python - 正则表达式:如果后面跟着一组运算符,如何捕获括号组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51973598/