我需要限制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)
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)
要找到N个匹配并停止,可以使用re.finditer和itertools.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)