【发布时间】:2018-06-06 21:44:35
【问题描述】:
假设我有一个看起来像这样的字符串
test = 'this is a (meh) sentence that uses (random bits of meh2) and (this is silly)'
如果括号内包含单词“meh”,我只想提取文本。
执行常规的非贪婪正则表达式以匹配括号内的任何内容:
re.findall(r'\((.*?)\)', test)
返回
['meh', 'random bits of meh2', 'this is silly']
尝试这样做只包含第一个和第二个内容:
re.findall(r'\((.*meh.*?)\)', test)
返回
['meh) sentence that uses (random bits of meh2']
我想要一个正则表达式只返回
['meh', 'random bits of meh2']
有人可以帮忙吗?谢谢!
【问题讨论】:
-
使第一个
.*不贪婪。 -
^yup:
\((.*?meh.*?)\) -
啊,错过了那个。谢谢!
标签: python regex python-3.x