How To Correctly Parse Closing Parentheses
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 P
Solution 1:
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)
^ ^ ^ ^
Post a Comment for "How To Correctly Parse Closing Parentheses"