gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:06:51 27 4
gpt4 key购买 nike

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

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

(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com