使用string进行Python对象匹配

时间:2015-03-10 08:48:15

标签: python regex string pattern-matching

为什么我找不到比赛?

>>> ti = "abcd"
>>> tq = "abcdef"
>>> check_abcd = re.compile('^abcd')
>>> if check_abcd.search(ti) is check_abcd.search(tq):
...     print "Matching"
... else:
...     print "not matching"
...
not matching

尽管变量ti和tq都匹配且具有相同的参考

>>> print check_abcd.search(ti)
<_sre.SRE_Match object at 0x7ffbb05559f0>
>>> print check_abcd.search(tq)
<_sre.SRE_Match object at 0x7ffbb05559f0>

为什么不匹配?

1 个答案:

答案 0 :(得分:2)

`is` is identity testing, == is equality testing. 
 is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

您可能希望匹配values而不是objects。因此您可以使用

ti = "abcd"
tq = "abcdef"
check_abcd = re.compile('^abcd')

if check_abcd.search(ti).group(0) == check_abcd.search(tq).group(0):
    print "Matching"
else:
    print "not matching"