SpanishBoy
SpanishBoy

Reputation: 2225

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 Party)

I want to extract both (You Gotta) and (to Party)

Upvotes: 1

Views: 889

Answers (1)

Kasravnd
Kasravnd

Reputation: 107357

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)
^         ^                      ^        ^

Upvotes: 4

Related Questions