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

qra*_*raq 7 python regex

我需要限制re.findall找到前3个匹配然后停止.

例如

text = 'some1 text2 bla3 regex4 python5'
re.findall(r'\d',text)
Run Code Online (Sandbox Code Playgroud)

然后我得到:

['1', '2', '3', '4', '5']
Run Code Online (Sandbox Code Playgroud)

而且我要:

['1', '2', '3']
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 8

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

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


unu*_*tbu 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']
Run Code Online (Sandbox Code Playgroud)