Thursday, October 6, 2022

Regex - findIter and findall

 The re.finditer() works exactly the same as the re.findall() method except it returns an iterator yielding match objects matching the regex pattern in a string instead of a list.

It scans the string from left to right, and matches are returned in the iterator form. Later, we can use this iterator object to extract all matches.

In simple words, finditer() returns an iterator over MatchObject objects.


But why use finditer()?

In some scenarios, the number of matches is high, and you could risk filling up your memory by loading them all using findall(). Instead of that using the finditer(), you can get all possible matches in the form of an iterator object, which will improve performance.

It means, finditer() returns a callable object which will load results in memory when called. 

references:

https://pynative.com/python-regex-findall-finditer/#:~:text=finditer()%20works%20exactly%20the,returned%20in%20the%20iterator%20form.

No comments:

Post a Comment