Extract string within parentheses - PYTHON

谁说我不能喝 提交于 2019-11-30 21:46:41
Maroun

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

as an improvement on @Maroun Maroun 's answer:

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

it finds all instances of strings in between parentheses

You can use split as in your example but this way

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

or using regex

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!