在括号之间返回文本的正则表达式

问题:在括号之间返回文本的正则表达式

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

我需要的只是括号内的内容。

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

All I need is the contents inside the parenthesis.


回答 0

如果您的问题确实如此简单,则不需要正则表达式:

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

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

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

回答 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'"

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

回答 2

如果要查找所有事件:

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

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

回答 3

如果您碰巧像这样嵌套嵌套括号,请以tkerwin的答案为基础

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

如果您需要将第一个开括号最后一个闭括号之间的所有内容都取成get (a+b)/(c+d),他的答案将不起作用,因为find从字符串的左侧开始搜索,并且会在第一个闭括号处停止。

要解决此问题,您需要使用rfind该操作的第二部分,因此它将变成

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

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

回答 4

import re

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

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

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

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

回答 5

contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])
contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])