【问题标题】:Find first x matches with re.findall使用 re.findall 查找前 x 个匹配项
【发布时间】:2014-04-20 17:14:54
【问题描述】:

我需要 limit re.findall 来查找前 3 个匹配项,然后停止。

例如

text = 'some1 text2 bla3 regex4 python5'
re.findall(r'\d',text)

然后我得到:

['1', '2', '3', '4', '5']

我想要:

['1', '2', '3']

【问题讨论】:

标签: python regex


【解决方案1】:

re.findall 返回一个列表,所以最简单的解决方案就是使用slicing

>>> import re
>>> text = 'some1 text2 bla3 regex4 python5'
>>> re.findall(r'\d', text)[:3]  # Get the first 3 items
['1', '2', '3']
>>>

【讨论】:

    【解决方案2】:

    要找到 N 个匹配项并停止,您可以使用 re.finditeritertools.islice

    >>> import itertools as IT
    >>> [item.group() for item in IT.islice(re.finditer(r'\d', text), 3)]
    ['1', '2', '3']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多