7

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

for example

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

then I get:

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

and I want:

['1', '2', '3']
qraq
  • 318
  • 3
  • 11

2 Answers2

10

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

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

To find N matches and stop, you could 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']
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677