【问题标题】:Python compiled pattern match with flags, cp.search to match at beginning of linePython 编译的带有标志的模式匹配,cp.search 在行首匹配
【发布时间】:2017-08-28 02:31:00
【问题描述】:

我有这个,不匹配,为什么?:

>>> p = r'abc'
>>> cp = re.compile(p, re.IGNORECASE)
>>> m = cp.search('ABC', re.IGNORECASE)
>>> m # NO MATCH # 1

但是,这给出了一个匹配,为什么?

>>> m = cp.search('  ABC', re.IGNORECASE) # introduced spaces, ABC no longer at the beginning 
>>> m # MATCH # 2
<_sre.SRE_Match object at 0x1082b5ac0>

要在 #1 中获得匹配,我所要做的就是放弃 re.IGNORECASE,为什么会这样?

>>> m = cp.search('ABC')
>>> m
<_sre.SRE_Match object at 0x10827e308>

【问题讨论】:

    标签: python regex python-2.7


    【解决方案1】:

    如果(在解释器中)您在 cp.search 上打印出帮助:

    help(cp.search)
    

    你会看到:

    Help on built-in function search:
    search(string=None, pos=0, endpos=9223372036854775807, *, pattern=None) method of _sre.SRE_Pattern instance
        Scan through string looking for a match, and return a corresponding match object instance.
    
        Return None if no position in the string matches.
    

    请注意,此函数不带任何标志,而是您实际将标志传递给“pos”参数的原因,这就是您得到意外结果的原因。

    【讨论】:

    • 您是如何在您的方法帮助中获得pos=0, endpos=9223372036854775807 的?我不这么认为。但是你说的完全有道理。谢谢
    • @abc 不知道,也许我们正在运行不同版本的 Python。
    • $ python --version Python 2.7.10
    • @abc 我使用的是 Python 3.6
    猜你喜欢
    • 2014-02-11
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2018-01-28
    相关资源
    最近更新 更多