为什么findall在与组匹配时不返回整个匹配?

2024-09-30 20:27:07 发布

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

正如我读到的,(dog|cat)food将查找dog food和{},但我无法在我的案例中重现它。在

>>> for m in re.findall('RA[a-zA-Z0-9]*',"RAJA45909"):
    print(m)


RAJA45909
>>> for m in re.findall('(ra|RA)[a-zA-Z0-9]*',"RAJA45909"):
    print(m)


RA
>>> 

有人能帮我理解一下吗。在


Tags: inreforfood案例catraprint
2条回答

您应该使用^{}而不是^{},然后打印整个匹配组:

>>> for m in re.finditer('(ra|RA)[a-zA-Z0-9]*',"RAJA45909"):
...     print(m.group())
... 
RAJA45909

findall的文档说明:

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

您的regex只有一个组,因此结果是该组匹配的文本列表。如果我们添加其他组,您会看到:

^{pr2}$

因此findall与groups一起使用时匹配整个regex,但只返回与组匹配的部分。而finditer总是返回一个完全匹配的对象。在

你可以用这个

print(re.findall('((?:ra|RA)[a-zA-Z0-9]*)',"RAJA45909"))

Ideone Demo

相关问题 更多 >