Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to return text between parenthesis

People also ask

How do you get a string between 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.

How do you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

What's the difference between () and [] in regular expression?

[] denotes a character class. () denotes a capturing group. (a-z0-9) -- Explicit capture of a-z0-9 . No ranges.


If your problem is really just this simple, you don't need regex:

s[s.find("(")+1:s.find(")")]

Use re.search(r'\((.*?)\)',s).group(1):

>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"

If you want to find all occurences:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']

Building on tkerwin's answer, if you happen to have nested parentheses like in

st = "sum((a+b)/(c+d))"

his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d), because find searches from the left of the string, and would stop at the first closing parenthesis.

To fix that, you need to use rfind for the second part of the operation, so it would become

st[st.find("(")+1:st.rfind(")")]