Skip to main content
 首页 » 编程设计

python之捕获两个单词之间的字符串,但只有第一次

2025年05月04日2298°冷暖

我有这样的字符串:

 text = "Why do Humans need to eat food? Humans eat food to survive." 

我想捕捉 Human 和 food 之间的一切,但只有第一次。

预期输出

Humans need to eat food 

我的正则表达式:

p =r'(\bHumans?\b.*?\bFoods?\b)' 

Python 代码:

re.findall(p, text, re.I|re.M|re.DOTALL) 

代码正确捕获了 Human 和 Food 之间的字符串,但它并没有在第一次捕获时停止。

研究:

我已经读过要使其非贪婪,我需要放置 ? 但我无法弄清楚应该将其保存在哪里以使其非贪婪。我尝试过的所有其他排列和组合都无法在第一场比赛中停止。

更新

我正在编写大量正则表达式来捕获像这样的各种其他实体并一次性解析它们,因此我无法更改我的 re.findall 逻辑。

请您参考如下方法:

使用search代替findall:

import re 
text = "Why do Humans need to eat food? Humans eat food to survive." 
p =r'(\bHumans?\b.*?\bFoods?\b)' 
res = re.search(p, text, re.I|re.M|re.DOTALL) 
print(res.groups()) 

输出:

('Humans need to eat food',) 

或者在正则表达式末尾添加.*:

import re 
text = "Why do Humans need to eat food? Humans eat food to survive." 
p =r'(\bHumans?\b.*?\bFoods?\b).*' 
#                      here ___^^ 
res = re.findall(p, text, re.I|re.M|re.DOTALL) 
print(res)