【问题标题】:Python re.match doesnt match the same regexpPython re.match 不匹配相同的正则表达式
【发布时间】:2013-12-17 21:22:20
【问题描述】:

我遇到了一个奇怪的问题;我希望以前没有人问过这个问题 我需要匹配两个包含 "(" ")" 的正则表达式。

这是我为看看为什么它不起作用所做的测试:

>>> import re
>>> re.match("a","a")
<_sre.SRE_Match object at 0xb7467218>

>>> re.match(re.escape("a"),re.escape("a"))
<_sre.SRE_Match object at 0xb7467410>

>>> re.escape("a(b)")
'a\\(b\\)'

>>> re.match(re.escape("a(b)"),re.escape("a(b)"))

=> 不匹配

有人能解释一下为什么正则表达式不匹配吗?

非常感谢

【问题讨论】:

  • 正则表达式通常与自己匹配。这不是“找到这个字符串”;正则表达式是一种微型声明性编程语言。

标签: python regex


【解决方案1】:

您已经转义了特殊字符,因此您的正则表达式将匹配字符串 "a(b)",而不是字符串
'a\(b\)',它是 re.escape('a(b)') 的结果。

【讨论】:

    【解决方案2】:

    第一个参数是模式对象,第二个是你要匹配的实际字符串。你不应该逃避字符串本身。请记住,re.escape 转义正则表达式中的特殊字符。

    >>> help(re.match)
    Help on function match in module re:
    
    match(pattern, string, flags=0)
        Try to apply the pattern at the start of the string, returning
        a match object, or None if no match was found.
    
    >>> re.match(re.escape('a(b)'), 'a(b)')
    <_sre.SRE_Match object at 0x10119ad30>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多