如何正确解析右括号 [英] How to correctly parse closing parentheses
问题描述
我正在尝试使用以下命令解析字符串中的所有括号:
\((.+)\)
但不知道我应该如何重写下一个字符串的命令:
<块引用>(你必须)争取你的权利(参加派对)
我想同时提取(You Gotta) 和(派对)
你需要一个否定字符类而不是 .+
然后使用 re.findall()
:
请注意,这里您的正则表达式将匹配左括号和右括号之间的所有内容,其中包含以下部分:
(你必须)为你的权利而战(参加派对)^--------------这部分会匹配------^
但是通过使用否定字符类 [^()]+
它将匹配括号之间的所有内容,但括号文字除外.这使您的正则表达式引擎在每个右括号处停止.
(你必须)为你的权利而战(参加派对)^ ^ ^ ^
I am trying to parse all brackets in strings with following command:
\((.+)\)
but no clue how I should rewrite the command for next string:
(You Gotta) Fight For Your Right (to Party)
I want to extract both (You Gotta) and (to Party)
You need a negated character class instead of .+
and then use re.findall()
:
>>> s="(You Gotta) Fight For Your Right (to Party)"
>>>
>>> import re
>>> re.findall(r'\(([^()]+)\)',s)
['You Gotta', 'to Party']
Note that, here your regex will match every thing between an open parenthesis and an close parenthesis which would be contains the following part :
(You Gotta) Fight For Your Right (to Party)
^-------this part will be matched --------^
But by use of negated character class [^()]+
it will match every thing between parenthesis except parenthesis literals.Which makes your regex engine stops at each closing bracket.
(You Gotta) Fight For Your Right (to Party)
^ ^ ^ ^
这篇关于如何正确解析右括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!