(([^\(\)]+))
我上面的正则表达式捕获了表单每组括号之间的所有内容
(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)
子表达式递归整个模式。
你可以在这里尝试。
对于输入:
(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']