Regular expression to return text between parenthe

2019-01-01 15:49发布

问题:

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

All I need is the contents inside the parenthesis.

回答1:

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

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


回答2:

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\'\"


回答3:

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\']


回答4:

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(\")\")]


回答5:

import re

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

print re.compile( \"\\((.*)\\)\" ).search( fancy ).group( 1 )