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

标签 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

我不确定正则表达式是否可以做到这一点,或者最好的方法是什么?

最佳答案

您可以使用以下模式:

\(((?:[^()]+|(?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/

相关文章:

python - cx_Oracle.NotSupportedError : Python value of type tuple not supported

python - 计算 3D 球面掩膜的直径线

javascript - 无法理解 javascript String.match(regexp) 方法的行为

python - Concurrent.futures 使用指南——同时使用线程和处理的简单示例

html - 如何使 yattag 源格式更好?

python - Numpy issubdtype 给出 "TypeError: data type not understood"

python - 无法通过 ftplib (Python) 使用 IP 地址

c++ - 如果字符在引号之间则不匹配(AKA 具有编程字符串模式)

javascript - 带有特殊字符的坏词过滤器

python - 在python中递归打印钻石