来自re.search()和re.match()的相同结果是相同的,但通过比较运算符不相同

2024-05-23 19:46:13 发布

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

这是我的密码

phone_list = ['234-572-1236 Charles', '234-753-1234 Crystal', '874-237-7532 Meg']

import re
result1 = [re.match(r'\d{3}-\d{3}-\d{4}', n)   for n in phone_list]
result2 = [re.search(r'\d{3}-\d{3}-\d{4}', n)  for n in phone_list]

print(result1)
print(result2)

# why they are not the same?
print(result1    == result2)
print(result1[0] == result2[0])
print(result1[1] == result2[1])
print(result1[2] == result2[2])

我使用re.match()和re.search()获得相同的结果。 但是当用比较运算符比较结果时,它都给我假,为什么


Tags: inimportre密码forsearchmatchphone
2条回答

匹配类型没有__eq__方法。因此,只要没有eq方法,比较运算符就会比较两个对象的内存地址

__eq__

这是一个神奇的类方法,每当将该类的实例与另一个对象进行比较时,就会调用它。如果未实现此方法,则默认情况下==比较两个对象的内存地址

https://realpython.com/python-is-identity-vs-equality/#how-comparing-by-equality-works

由于匹配类型没有自定义的__eq__方法,因此相等操作将始终返回False,除非它是完全相同的匹配实例

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality.

https://docs.python.org/3/reference/expressions.html#value-comparisons

每次调用re.match或re.search时,返回值将是不同的匹配对象,即使输入数据完全相同

>>> needle, haystack = 's', 'spam'                                                                                                                                                                                                  
>>> re.match(needle, haystack) == re.match(needle, haystack)                                                                                                                                                                        
    False

相关问题 更多 >