捕获两个单词之间的字符串,但仅限于第一个

2024-06-16 10:41:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的字符串:

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

我想捕获Humanfood之间的所有内容,但只捕获第一次。你知道吗

预期产量

Humans need to eat food

我的正则表达式:

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

Python代码:

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

代码正确地捕获了人类和食物之间的字符串,但它不会在第一次捕获时停止。你知道吗

研究:

我读过,为了让它不贪婪,我需要把?放在哪里,但我不知道应该把它放在哪里,使它不贪婪。我尝试过的所有其他排列和组合在第一场比赛中都无法阻止。你知道吗

更新

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


Tags: to字符串代码textre内容foodneed
3条回答

使用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)

试试这个:

>>> import re
>>> text = "Why do Humans need to eat food? Humans eat food to survive."
>>> re.search(r'Humans.*?food', text).group() # you want the all powerful non-greedy '?' :)
'Humans need to eat food'

为了只找到第一个匹配项,Toto的答案是最好的,但是正如您所说的,您只需要使用findall,您可以在regex的末尾附加.*,以匹配剩余的文本,这不会导致任何进一步的匹配。你知道吗

(\bHumans?\b.*?\bFoods?\b).*
                          ^^ This eats remaining part of your text due to which there won't be any further matches.

Demo

Python代码示例

import re

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

指纹

['Humans need to eat food']

相关问题 更多 >