Search code examples
pythonregexcomparison-operators

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


here is my code,

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])

I use re.match() and re.search() to obtain the same result. but when compare the result by comparison operator, it all gives me False, why?


Solution

  • Because the Match type does not have a custom __eq__ method, the equality operation will always return False, unless it's the exact same Match instance.

    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

    Every time you call re.match or re.search, the return value will be a different Match object, even when the input data is exactly the same.

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