2014-04-20 129 views
7

我需要限制re.findall找到前3個匹配,然後停止。查找前x匹配re.findall

例如

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

然後我得到:

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

,我想:

['1', '2', '3'] 
+0

你可以在這裏看看:http://stackoverflow.com/questions/16235770/how-to- limit-regexs-findall-method –

+1

或更高版本:http://stackoverflow.com/questions/11902378/python-regular-expressions-limit-results –

回答

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'] 
8

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'] 
>>>