Extract string within parentheses - PYTHON

Olly_t picture Olly_t · Aug 17, 2016 · Viewed 21.3k times · Source

I have a string "Name(something)" and I am trying to extract the portion of the string within the parentheses!

Iv'e tried the following solutions but don't seem to be getting the results I'm looking for.

n.split('()')

name, something = n.split('()')

Answer

Maroun picture Maroun · Aug 17, 2016

You can use a simple regex to catch everything between the parenthesis:

>>> import re
>>> s = 'Name(something)'
>>> re.search('\(([^)]+)', s).group(1)
'something'

The regex matches the first "(", then it matches everything that's not a ")":

  • \( matches the character "(" literally
  • the capturing group ([^)]+) greedily matches anything that's not a ")"