Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit regex's findall() method

Is there a regex equivalent of BeautifulSoup's limit=X argument for the findall method? I mean, how to find the first X words in question and then break the code execution? thank you

like image 676
nutship Avatar asked Dec 02 '25 10:12

nutship


1 Answers

Use re.finditer and itertools.islice:

from itertools import islice
import re

limit = 2

for x in islice(re.finditer(r'\d+', '1 2 33'), limit):
    print(x.group())

As a function:

def findall_limiter(pattern, string, flags=0):
    return islice(re.finditer(pattern, string, flags), limit)

eg.

for match in findall_limiter(r'\d+', '1 2 33', 2):
    # do stuff
like image 95
gatto Avatar answered Dec 05 '25 00:12

gatto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!