qraq
qraq

Reputation: 318

Find first x matches with re.findall

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

Upvotes: 7

Views: 6552

Answers (2)

unutbu
unutbu

Reputation: 879163

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

Upvotes: 8

user2555451
user2555451

Reputation:

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

Upvotes: 10

Related Questions