The Python re.finditer() method returns an iterator yielding match objects for all non-overlapping matches of a pattern in a string.
The method re.findall() which returns a list of matched strings whereas the method re.finditer() provides more detailed information about each match such as the start and end positions within the string. Each match object can be used to extract matched substrings and their positions.
This method is particularly useful when we need to process or analyze each match in detail.
SyntaxFollowing is the syntax and parameters of Python re.finditer() method −
re.finditer(pattern, string, flags=0)Parameters
Following are the parameters of the python re.finditer() method −
This method returns an iterator of match objects
Example 1Following is the basic example of the re.finditer() method. This example finds all numeric sequences in the string and prints each match −
import re matches = re.finditer(r'\d+', 'There are 123 apples and 456 oranges.') for match in matches: print(match.group())Output
123 456Example 2
This example finds all words in the string and prints each word with the help of the method re.finditer() −
import re matches = re.finditer(r'\b\w+\b', 'Hello, world! Welcome to Python.') for match in matches: print(match.group())Output
Hello world Welcome to PythonExample 3
In this example we use the re.IGNORECASE flag to perform a case-insensitive search and prints each match −
import re matches = re.finditer(r'hello', 'Hello HELLO hello', re.IGNORECASE) for match in matches: print(match.group())Output
Hello HELLO helloExample 4
Here in this example we retrieve the start and end positions of each match in the string −
import re matches = re.finditer(r'\d+', 'There are 123 apples and 456 oranges.') for match in matches: print(match.group(), match.start(), match.end())Output
123 10 13 456 25 28
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4