Python re.finditer() method
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.
Syntax
Following 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 −
- pattern: The regular expression pattern to search for.
- string: The string to search within.
- maxsplit(optional): The maximum number of splits. Default value is 0 which means "no limit".
- flags(optional): Flags to modify the matching behavior (e.g., re.IGNORECASE)
Return value
This method returns an iterator of match objects
Example 1
Following 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 456
Example 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 Python
Example 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 hello
Example 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