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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With