Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

The `finditer()` function in the `re` module is used to find all occurrences of a pattern in a string and return an iterator yielding match objects. Each match object contains information about the matched substring, including its start and end positions within the original string. Here are several illustrative examples of using the `finditer()` function:

1. Finding All Instances of a Pattern:
“`python
import re

# Define the regex pattern
pattern = r’bd{3}b’ # Matches three-digit numbers

# Test string
test_string = “The numbers 123, 456, and 789 are examples of three-digit numbers.”

# Find all matches using finditer()
matches = re.finditer(pattern, test_string)

# Iterate over matches and print start and end positions
for match in matches:
print(“Match found at:”, match.start(), “-“, match.end(), “=>”, match.group())
“`

2. Extracting Email Addresses:
“`python
import re

# Define the regex pattern for email addresses
pattern = r’b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}b’

# Test string
test_string = “Contact us at support@example.com or info@example.org for assistance.”

# Find all email addresses using finditer()
matches = re.finditer(pattern, test_string)

# Iterate over matches and print them
for match in matches:
print(“Email address found:”, match.group())
“`

3. Detecting URLs:
“`python

import re

# Define the regex pattern for URLs
pattern = r’bhttps?://(www)?.([a-zA-Z]+.)?[a-zA-Z0-9]+.(com|net)b’ #r’bhttps?://(?:[-w.]|(?:%[da-fA-F]{2}))+b’

# Test string
test_string = “Visit our website at https://www.example.com for more information … and this website http://courses.africanstudents.net”

# Find all URLs using finditer()
matches = re.finditer(pattern, test_string)

# Iterate over matches and print them
for match in matches:
print(“URL found:”, match.group())

“`

4. Matching Words with a Specific Prefix:
“`python
import re

# Define the regex pattern for words starting with ‘pre’
pattern = r’bprew+b’

# Test string
test_string = “The words pretest, prepare, and preview all start with the prefix ‘pre’.”

# Find all matches using finditer()
matches = re.finditer(pattern, test_string)

# Iterate over matches and print them
for match in matches:
print(“Word with ‘pre’ prefix found:”, match.group())
“`

These examples demonstrate how the `finditer()` function can be used to locate all occurrences of a pattern within a string and extract relevant information from text data.

Join the conversation