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

same result from both re.search() and re.match() are the same, but not the same by comparison operator

这是我的代码,

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() 获得相同的结果。 但是当用比较运算符比较结果时,结果都是False,为什么?

因为 Match 类型没有自定义 __eq__ 方法,相等操作将始终 return False,除非它是完全相同的 Match 实例。

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 时,return 值将是不同的 Match 对象,即使输入数据完全相同。

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

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

__eq__

这是一个神奇的 class 方法,只要将此 class 的实例与另一个对象进行比较,就会调用该方法。如果没有实现这个方法,那么==默认比较两个对象的内存地址。

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