【问题标题】:Python object matching using string使用字符串匹配 Python 对象
【发布时间】:2015-03-10 08:48:14
【问题描述】:

为什么我找不到匹配项?

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

为什么不匹配?

【问题讨论】:

  • 试试if check_abcd.search(ti).group() == check_abcd.search(tq).group():
  • 将这两个对象存储在单独的变量中,然后尝试。那么他们的 ID 就会不同(因为旧的对象会被覆盖)

标签: python regex string pattern-matching


【解决方案1】:
`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"

【讨论】:

  • 嘿vks! OP 似乎在询问为什么 is 运算符不起作用,即使对象引用指向相同的 ID。你的答案很完美!但请保持等待,直到 OP 澄清 :)
  • 不!他们会被覆盖。这就是为什么我也在待命:) Check this comment
  • 是的 vks 和 Bhargav,== 与 group 作为属性一起使用时工作正常。我认为即使对象引用相同的 id,为什么即使我使用 == 或 is,它也不匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多