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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4894069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:00:42  来源:igfitidea点击:

Regular expression to return text between parenthesis

pythonregexpython-3.x

提问by user469652

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

All I need is the contents inside the parenthesis.

我只需要括号内的内容。

采纳答案by tkerwin

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

如果你的问题真的就这么简单,你就不需要正则表达式:

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

回答by waan

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

回答by Anonymous

import re

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

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

回答by TheSoulkiller

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

回答by FaustoW

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

基于 tkerwin 的答案,如果您碰巧有嵌套括号,例如

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

his answer will not work if you need to take everything between the firstopening parenthesisand the lastclosing parenthesisto 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),因为find搜索左边的字符串,并会在第一右括号停止。

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

为了解决这个问题,你需要使用rfind操作的第二部分,所以它会变成

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

回答by surfer190

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