Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('()')
like image 888
Olly_t Avatar asked Aug 17 '16 14:08

Olly_t


People also ask

How do you extract a string in parentheses in Python?

The simplest way to extract the string between two parentheses is to use slicing and string. find() . First, find the indices of the first occurrences of the opening and closing parentheses. Second, use them as slice indices to get the substring between those indices like so: s[s.


4 Answers

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 ")"
like image 86
Maroun Avatar answered Oct 03 '22 07:10

Maroun


as an improvement on @Maroun Maroun 's answer:

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

it finds all instances of strings in between parentheses

like image 40
tamtam Avatar answered Oct 03 '22 07:10

tamtam


You can use split as in your example but this way

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

or using regex

like image 32
Luca Avatar answered Oct 03 '22 05:10

Luca


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 \( & \).

like image 28
Ohad Eytan Avatar answered Oct 03 '22 05:10

Ohad Eytan