2024-09-30 20:27:07 发布
网友
正如我读到的,(dog|cat)food将查找dog food和{},但我无法在我的案例中重现它。在
(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 >>>
有人能帮我理解一下吗。在
您应该使用^{}而不是^{},然后打印整个匹配组:
>>> for m in re.finditer('(ra|RA)[a-zA-Z0-9]*',"RAJA45909"): ... print(m.group()) ... RAJA45909
findall的文档说明:
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只有一个组,因此结果是该组匹配的文本列表。如果我们添加其他组,您会看到:
因此findall与groups一起使用时匹配整个regex,但只返回与组匹配的部分。而finditer总是返回一个完全匹配的对象。在
finditer
你可以用这个
print(re.findall('((?:ra|RA)[a-zA-Z0-9]*)',"RAJA45909"))
Ideone Demo
您应该使用^{} 而不是^{} ,然后打印整个匹配组:
findall
的文档说明:您的regex只有一个组,因此结果是该组匹配的文本列表。如果我们添加其他组,您会看到:
^{pr2}$因此
findall
与groups一起使用时匹配整个regex,但只返回与组匹配的部分。而finditer
总是返回一个完全匹配的对象。在你可以用这个
Ideone Demo
相关问题 更多 >
编程相关推荐