使用re.findall找到前x个匹配项

7 投票
2 回答
6522 浏览
提问于 2025-04-18 03:30

我想限制 re.findall 这个函数,只找到前3个匹配项,然后就停止。

比如说:

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

这样我得到的是:

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

而我想要的是:

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

2 个回答

10

re.findall 是一个函数,它会返回一个列表。所以最简单的解决办法就是直接使用切片的方法:

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

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

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

撰写回答