我有这样的字符串:
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)
代码正确地捕获了人类和食物之间的字符串,但它不会在第一次捕获时停止。你知道吗
研究:
我读过,为了让它不贪婪,我需要把?
放在哪里,但我不知道应该把它放在哪里,使它不贪婪。我尝试过的所有其他排列和组合在第一场比赛中都无法阻止。你知道吗
更新
我编写了很多正则表达式来捕获像这样的各种其他实体,并一次性解析它们,因此我无法更改我的re.findall
逻辑。你知道吗
使用
search
而不是findall
:输出:
或者在正则表达式的末尾添加
.*
:试试这个:
为了只找到第一个匹配项,Toto的答案是最好的,但是正如您所说的,您只需要使用
findall
,您可以在regex的末尾附加.*
,以匹配剩余的文本,这不会导致任何进一步的匹配。你知道吗Demo
Python代码示例
指纹
相关问题 更多 >
编程相关推荐