Python 括号内的非贪婪正则表达式,包含文本

Python 括号内的非贪婪正则表达式,包含文本,python,regex,python-3.x,Python,Regex,Python 3.x,假设我有一根像 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'] ['meh) sentence that u

假设我有一根像

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']
['meh) sentence that uses (random bits of meh2']
尝试仅包含第一个和第二个内容:

re.findall(r'\((.*meh.*?)\)', test)
返回

['meh', 'random bits of meh2', 'this is silly']
['meh) sentence that uses (random bits of meh2']
我只想要一个正则表达式返回

['meh', 'random bits of meh2']

有人能帮忙吗?谢谢

您可以通过使用
[^\)]
来允许除闭括号以外的所有字符,而不是允许所有字符,其中
现在是

re.findall(r'\(([^\)]*meh[^\)]*?)\)', test)

让第一个
*
不贪婪。^yup:
\(.*?meh.*?)
啊,错过了那个。谢谢<代码>r'\(.*?meh.*?)'不起作用。它应该是
re.findall(r'\([^()]*meh[^()]*)\),test)
code不鼓励只回答代码。你能描述一下OP的代码为什么不起作用,以及它可能起作用的区别吗?@WiktorStribiżew-为什么非贪婪不起作用?我一直喜欢
[^()]
方法,因为它感觉更明确,但我想不出任何具体的例子可以打破非贪婪。@zzxyz With
这是一个(meh)句子,使用(meh2的随机位)和(这是愚蠢的)
,它只是一个巧合
\(.*meh.*?)
起作用。你。@WiktorStribiżew-啊,是的……懒惰,但正则表达式尽快开始。非常感谢。有趣的是,比较regex101.com上的两个选项,该版本在~4ms时使用了131个步骤,而非贪婪版本在~1ms时使用了146个步骤。