gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:37 26 4
gpt4 key购买 nike

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

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)

关于python - 括号内的非贪婪正则表达式并包含文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50730070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com