Regular expression to return text between brackets

u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')' 

All I need is the contents inside the parenthesis.

+49
python regex
04 Feb 2018-11-11T00:
source share
5 answers

If your problem is really that simple, you don't need a regex:

 s[s.find("(")+1:s.find(")")] 
+123
04 Feb 2018-11-11T00:
source share

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'" 
+26
Feb 04 2018-11-11T00:
source share

If you want to find all occurrences:

 >>> 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'] 
+17
Jul 10 '15 at 14:49
source share

Based on tkerwin's answer if you 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 bracket and the last closing parenthesis to get (a+b)/(c+d) , because it searches for searches on the left of the line and stops in the first closing bracket.

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

 st[st.find("(")+1:st.rfind(")")] 
+4
Nov 25 '16 at 20:37
source share
 import re fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')' print re.compile( "\((.*)\)" ).search( fancy ).group( 1 ) 
+2
Feb 04 2018-11-11T00:
source share



All Articles