Are you searching for How to use finditer python? This article will briefly explain the finditer() function in re module with syntax and programming examples.
When to use the finditer() function re module in python?
If you are trying to extract the occurrence details of any pattern in the text with python. You must use the “re” module in python. In the “re” module of python, You may use the search function with text and pattern as an argument. This search function will give you the match object. But there is a limitation that It will provide only the first occurrence of the pattern. Firstly, Let’s see the below example –
import re text= 'My home town is a big town' pattern = 'town' match_obj=re.search(pattern,text) span =match_obj.span() print(span)Here is the output -
In the above example, you have seen the search function only extract the detail of the first occurrence of pattern. Now how to extract the complete occurrence of the pattern? Answer is finditer() function .
How to use finditer python?
finditer() function is quite similar to the search function of ‘re’. Actually finditer() functions return an iterator object, In the opposite direction search function returns a single match object. Let’s understand how to implement finditer() function in python –
import re text= 'My home town is a big town' pattern = 'town' match_obj=re.finditer(pattern,text) for match in match_obj: print(match.span())
Here is the output of the above complete coding example for finditer() demonstration.
We have iterated the match_obj object (variable) in the above example. This is a return type of finditer() function. Here we have used the span() function for demonstration of the iterable object. But we can also use other properties and function in this place.
Moreover, If you need to know more about the regular expression module re in python, Visit the official documentation of re module.
Text Mining is the first step towards Natural Language Processing. The re module in Python provides a strong grip in Text Mining. We will keep writing articles on Text Mining and NLP.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.