This post explains how to use re.finditer
method in Python.
re.finditer
function syntax
re.finditer(pattern, string, flags=0)
re.finditer
method returns an iterator over all non-overlapping matches in the string. For each match, the iterator returns a Match object. Below are some of the example for using re.finditer
.
1. Finding all Adverbs and their Positions using re.finditer
in Python
import re
sample_str = """The teacher firmly disciplined the students for their misbehavior.
The beautifully painted landscape is a wonderful addition to my living room decor.
"""
for m_object in re.finditer(r"\w+ly\b", sample_str):
print(f"{m_object.start()} {m_object.end()} {m_object.group(0)}")
# Output
12 18 firmly
71 82 beautifully
2. Extracting domain name from text using re.finditer
import re
text = """Extract domain from this string. url for gcptutorials www.gcptutorials.com,
url for wikipedia www.wikipedia.org"""
pattern = r'(www.([A-Za-z_0-9-]+)(.\w+))'
find_iter_result = re.finditer(pattern, text)
for i in find_iter_result:
print(i.group(2))
# Output
gcptutorials
wikipedia
Similar Articles