【问题标题】:Python RE - different matching for finditer and findallPython RE - finditer 和 findall 的不同匹配
【发布时间】:2011-04-18 05:24:57
【问题描述】:

这里有一些代码:

>>> p = re.compile(r'\S+ (\[CC\] )+\S+')
>>> s1 = 'always look [CC] on the bright side'
>>> s2 = 'always look [CC] [CC] on the bright side'
>>> s3 = 'always look [CC] on the [CC] bright side'
>>> m1 = p.search(s1)
>>> m1.group()
'look [CC] on'
>>> p.findall(s1)
['[CC] ']
>>> itr = p.finditer(s1)
>>> for i in itr:
...     i.group()
... 
'look [CC] on'

显然,这与查找 s3 中 findall 返回的所有匹配项更相关:['[CC]', '[CC]'],因为 findall 似乎只匹配 p 中的内部组,而 finditer 匹配整个图案。

为什么会这样?

(我像我一样定义了 p,以便允许捕获包含 [CC] 序列的模式,例如 s2 中的“look [CC] [CC] on”)。

谢谢

【问题讨论】:

    标签: python regex findall


    【解决方案1】:

    i.group() 返回整个匹配项,包括组前后的非空白字符。要获得与 findall 示例相同的结果,请使用 i.group(1)

    http://docs.python.org/library/re.html#re.MatchObject.group

    In [4]: for i in p.finditer(s1):
    ...:     i.group(1)
    ...:     
    ...:     
    Out[4]: '[CC] '
    

    【讨论】:

    • 我不确定我是否理解。 findall() 返回匹配字符串的列表。如何在其输出中使用 group(1)?
    • 不,您对从p.finditer(s1) 返回的迭代器中的元素使用组。我在回答中添加了一个示例。
    • 啊,谢谢。我知道如何将 group(1) 与迭代器一起使用。问题是我想要与 finditer 相同的结果 - 我确实想要获得整个模式。我不明白 findall 怎么没有返回完整的模式。
    • 记录在案的行为:“如果模式中存在一个或多个组,则返回组列表”,docs.python.org/library/re.html#re.findall
    • 谢谢。我没有注意到这一点。这基本上意味着我必须将整个模式定义为外部组: p = re.compile(r'(\S+ (\[CC\] )+\S+)') 然后只使用每个元组中的第一个元素在返回的元组列表中。或者干脆使用 finditer() :)
    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 2023-01-25
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多