Olly_t
Olly_t

Reputation: 261

Extract string within parentheses - PYTHON

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('()')

Upvotes: 26

Views: 44550

Answers (5)

Rithin Chalumuri
Rithin Chalumuri

Reputation: 1839

You can look for ( and ) (need to escape these using backslash in regex) and then match every character using .* (capturing this in a group).

Example:

import re

s = "name(something)"

regex = r'\((.*)\)'

text_inside_paranthesis = re.match(regex, s).group(1)

print(text_inside_paranthesis)

Outputs:

something

Without regex you can do the following:

text_inside_paranthesis =  s[s.find('(')+1:s.find(')')]

Outputs:

something

Upvotes: 0

Maroun
Maroun

Reputation: 95958

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

Upvotes: 33

tamtam
tamtam

Reputation: 701

as an improvement on @Maroun Maroun 's answer:

re.findall('\(([^)]+)', s)

it finds all instances of strings in between parentheses

Upvotes: 17

Ohad Eytan
Ohad Eytan

Reputation: 8464

You can use re.match:

>>> import re
>>> s = "name(something)"
>>> na, so = re.match(r"(.*)\((.*)\)" ,s).groups()
>>> na, so
('name', 'something')

that matches two (.*) which means anything, where the second is between parentheses \( & \).

Upvotes: 2

Luca
Luca

Reputation: 1626

You can use split as in your example but this way

val = s.split('(', 1)[1].split(')')[0]

or using regex

Upvotes: 5

Related Questions