【问题标题】:different behavior when using re.finditer and re.match使用 re.finditer 和 re.match 时的不同行为
【发布时间】:2011-01-10 12:39:13
【问题描述】:

我正在研究一个正则表达式,以通过一些脚本从页面中收集一些值。我在条件中使用re.match 但它返回false 但如果我使用finditer 它返回true 并执行条件主体。我在自己构建的测试器中测试了该正则表达式,它在那里工作,但不是在脚本中。 这是示例脚本。

result = []
RE_Add0 = re.compile("\d{5}(?:(?:-| |)\d{4})?", re.IGNORECASE)
each = ''Expiration Date:\n05/31/1996\nBusiness Address: 23901 CALABASAS ROAD #2000 CALABASAS, CA 91302\n'
if RE_Add0.match(each):
    result0 = RE_Add0.match(each).group(0)
    print result0
    if len(result0) < 100:
        result.append(result0)
    else:
        print 'Address ignore'
else:
    None

【问题讨论】:

    标签: python regex python-2.5


    【解决方案1】:

    re.finditer() 即使没有匹配项也会返回一个迭代器对象(因此if RE_Add0.finditer(each) 将始终返回True)。您必须实际迭代对象以查看是否存在实际匹配项。

    那么,re.match() 只匹配字符串的开头,而不是字符串中的任何位置,如 re.search()re.finditer() 那样。

    第三,正则表达式可以写成r"\d{5}(?:[ -]?\d{4})"

    第四,始终使用带有正则表达式的原始字符串。

    【讨论】:

      【解决方案2】:

      re.match 只匹配字符串的开头一次。 re.finditer 在这方面类似于 re.search,即它是迭代匹配的。比较:

      >>> re.match('a', 'abc')
      <_sre.SRE_Match object at 0x01057AA0>
      >>> re.match('b', 'abc')
      >>> re.finditer('a', 'abc')
      <callable_iterator object at 0x0106AD30>
      >>> re.finditer('b', 'abc')
      <callable_iterator object at 0x0106EA10>
      

      ETA:既然你提到了 page,我只能推测你在谈论 html 解析,如果是这样,请使用 BeautifulSoup 或类似的 html 解析器。不要使用正则表达式。

      【讨论】:

      • 那么你能帮我如何执行这个脚本吗?我坚持了最后 6 个小时。没有找到解决方案:-(不幸的是我不是一个好的程序员:-(
      【解决方案3】:

      试试这个:

      import re
      
      postalCode = re.compile(r'((\d{5})([ -])?(\d{4})?(\s*))$')
      primaryGroup = lambda x: x[1]
      
      sampleStr = """
          Expiration Date:
          05/31/1996
          Business Address: 23901 CALABASAS ROAD #2000 CALABASAS, CA 91302  
      """
      result = []
      
      matches = list(re.findall(postalCode, sampleStr))
      if matches:
          for n,match in enumerate(matches): 
              pc = primaryGroup(match)
              print pc
              result.append(pc)
      else:
          print "No postal code found in this string"
      

      这会在任何一个上返回“12345”

      12345\n
      12345  \n
      12345 6789\n
      12345 6789    \n
      12345 \n
      12345     \n
      12345-6789\n
      12345-6789    \n
      12345-\n
      12345-    \n
      123456789\n
      123456789    \n
      12345\n
      12345    \n
      

      我只在行尾匹配,否则在您的示例中它也匹配“23901”(来自街道地址)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-07
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2013-04-01
        相关资源
        最近更新 更多