【问题标题】:Regex - match returns None. Where am I wrong?正则表达式 - 匹配返回无。我哪里错了?
【发布时间】:2012-10-22 15:25:59
【问题描述】:
>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None

在与 s 末尾的测试匹配的 Kiki 中。我想念什么? (我也试过re.compile(r'test$')

【问题讨论】:

    标签: python regex


    【解决方案1】:

    使用

    match1 = reg1.search(s)
    

    相反。 match 函数 only 匹配字符串的开头...参见文档here:

    Python 提供了两种基于正则表达式的不同原始操作:re.match() 仅在字符串的开头检查匹配,而re.search() 在字符串中的任何位置检查匹配(这是 Perl 默认所做的) .

    【讨论】:

    • 谢谢,我完全忘记了这两个操作的区别:)
    • 谢谢!但是 match() 的这种奇怪行为 :(( 我现在花了两个小时,试图找出 rx 中的问题 lol
    • 泰。恕我直言,这完全违反直觉......
    【解决方案2】:

    您的正则表达式不匹配完整的字符串。您可以使用 search 来代替 Useless 提到的,或者您可以更改您的正则表达式以匹配完整的字符串:

    '^this is a test$'
    

    或者有些难以阅读,但没那么无用:

    '^t[^t]*test$'
    

    这取决于你想要做什么。

    【讨论】:

      【解决方案3】:

      这是因为 match 方法如果找不到预期的模式,则返回 None,如果找到模式,它将返回一个类型为 _sre.SRE_match 的对象。

      因此,如果您想要来自 match 的布尔(TrueFalse)结果,您必须检查结果是否为 None

      您可以像这样检查文本是否匹配:

      string_to_evaluate = "Your text that needs to be examined"
      expected_pattern = "pattern"
      
      if re.match(expected_pattern, string_to_evaluate) is not None:
          print("The text is as you expected!")
      else:
          print("The text is not as you expected!")
      

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多