u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
All I need is the contents inside the parenthesis.
我所需要的只是括号内的内容。
5 个解决方案
#1
147
If your problem is really just this simple, you don't need regex:
如果你的问题真的很简单,你不需要regex:
s[s.find("(")+1:s.find(")")]
#2
35
Use re.search(r'\((.*?)\)',s).group(1)
:
使用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
20
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
8
Building on tkerwin's answer, if you happen to have nested parentheses like in
构建在tkerwin的答案之上,如果您碰巧有嵌套圆括号,比如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.
如果您需要在第一个开括号和最后一个圆括号(a+b)/(c+d)之间进行所有的操作,因为在字符串的左侧找到搜索,并且在第一个闭括号中停止,那么他的答案将不会起作用。
To fix that, you need to use rfind
for the second part of the operation, so it would become
要解决这个问题,您需要对操作的第二部分使用rfind,这样它就会变成
st[st.find("(")+1:st.rfind(")")]
#5
3
import re
fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )
#1
147
If your problem is really just this simple, you don't need regex:
如果你的问题真的很简单,你不需要regex:
s[s.find("(")+1:s.find(")")]
#2
35
Use re.search(r'\((.*?)\)',s).group(1)
:
使用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
20
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
8
Building on tkerwin's answer, if you happen to have nested parentheses like in
构建在tkerwin的答案之上,如果您碰巧有嵌套圆括号,比如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.
如果您需要在第一个开括号和最后一个圆括号(a+b)/(c+d)之间进行所有的操作,因为在字符串的左侧找到搜索,并且在第一个闭括号中停止,那么他的答案将不会起作用。
To fix that, you need to use rfind
for the second part of the operation, so it would become
要解决这个问题,您需要对操作的第二部分使用rfind,这样它就会变成
st[st.find("(")+1:st.rfind(")")]
#5
3
import re
fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )