正则表达式:如果后跟一组运算符,如何捕获括号组?
Regex: How to capture groups of parentheses if followed by a set of operators?
\(([^\(\)]+)\)
我上面的正则表达式捕获了
形式的每组括号之间的所有内容
(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)
Returns
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']
\(([^\(\)]+)\)
我上面的正则表达式捕获了
形式的每组括号之间的所有内容(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)
Returns
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']