Skip to main content
 首页 » 编程设计

python之括号内的非贪婪正则表达式并包含文本

2024年08月15日43落叶无声

假设我有一个字符串看起来像

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

有人可以帮忙吗?谢谢!

请您参考如下方法:

除了允许所有字符外,您还可以使用 [^\)] 允许除右括号之外的所有字符,其中 . 现在是

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