Find first matches of x with re.findall

I need to restrict re.findall to find the first 3 matches and then stop.

eg

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

then I get:

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

I want too:

 ['1', '2', '3'] 
+7
python regex
source share
2 answers

To find N matches and stop, you can use re.finditer and itertools.islice :

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

re.findall returns a list, so the easiest solution would be to simply use slicing :

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

All Articles