Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
PYTHON PROGRAMMING
UNIT 4: REGULAR EXPRESSIONS & EXCEPTION
HANDLING
COMPLETE 16-MARK EXAM PREPARATION NOTES
ah
Subject Python Programming
Unit Unit 4
Topics Covered
Document Type
Prepared By
Sh Regular Expressions, Exception
Handling
University Exam Preparation Material
Senior Professor – Python & Regex
Expert
Exam Pattern 16-Mark Long Answer Questions
Level Undergraduate / Postgraduate
h
ris
"Master Regex. Ace Your Exams. Build Real-World Python Skills."
SYLLABUS COVERAGE
K
Unit 4 – Complete Syllabus
1. Regular Expressions – Powerful Pattern Matching and Searching
2. Power of Pattern Searching using Regex in Python
3. Real-time Parsing of Data using Regex
4. Password Validation using Regular Expressions
5. Email Validation using Regular Expressions
6. URL Validation using Regular Expressions
7. Pattern Finding Programs using Regular Expressions
8. Exception Handling in Python
Unit 4 | Regular Expressions & Exception HandlingPage 1
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
SECTION 1: INTRODUCTION TO REGULAR EXPRESSIONS
QUESTION 1 (16 Marks): Explain Regular Expressions in Python in detail. Describe the re module and
its key functions with syntax, examples, and output. Also explain the difference between [Link]() and
[Link]().
1.1 Introduction to Regular Expressions
A Regular Expression (also called Regex or RE) is a special sequence of characters that defines a
search pattern. It is used to check if a string matches a particular pattern, or to find/replace substrings
within text.
Regular expressions are extremely powerful tools widely used in:
• Text search and manipulation (e.g., searching logs, documents)
ah
• Data validation (email, password, URL, phone number)
• Web scraping and data parsing
• Compiler design (tokenizing source code)
• Network security (intrusion detection, firewall rules)
1.2 The re Module in Python
Sh
Python provides the built-in re module for working with regular expressions. It implements Perl-like
regular expression operations and must be imported before use.
import re # Always import the re module first
1.3 Key Functions of the re Module
Function Description & Return Value
h
[Link](p, s) Matches pattern p only at the BEGINNING of string s. Returns
match object or None.
ris
[Link](p, s) Scans through string s looking for the FIRST location where
pattern p produces a match. Returns match object or None.
[Link](p, s) Returns a LIST of all non-overlapping matches in the string.
Empty list if no match.
[Link](p, s) Returns an ITERATOR yielding match objects for all
non-overlapping matches.
K
[Link](p, repl, s) Returns string with all occurrences of pattern p replaced by
repl.
[Link](p, repl, s) Like sub() but also returns the number of substitutions made as
a tuple.
[Link](p, s) Splits string s by occurrences of pattern p. Returns a list.
[Link](p) Compiles a regex pattern into a regex object for repeated use
(more efficient).
[Link](p, s) Matches pattern p against the ENTIRE string s. Returns match
object or None.
Unit 4 | Regular Expressions & Exception HandlingPage 2
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
1.4 Syntax of Key Functions
# Syntax:
[Link](pattern, string, flags=0)
[Link](pattern, string, flags=0)
[Link](pattern, string, flags=0)
[Link](pattern, repl, string, count=0, flags=0)
[Link](pattern, string, maxsplit=0, flags=0)
[Link](pattern, flags=0)
1.5 Match Object Methods
ah
Match Object Method Description
[Link]() Returns the entire matched string
[Link](n) Returns the nth captured group
[Link]() Returns all captured groups as a tuple
[Link]() Returns the starting index of the match
[Link]()
[Link]()
1.6 [Link]() – Complete Example
Sh
Returns the ending index of the match
Returns a tuple (start, end) of the match
The [Link]() function tries to match the pattern only at the BEGINNING of the string.
import re
h
# Example 1: Successful match at beginning
result = [Link](r'Hello', 'Hello World')
if result:
ris
print('Match found:', [Link]()) # Output: Match found: Hello
print('Start:', [Link]()) # Output: Start: 0
print('End:', [Link]()) # Output: End: 5
# Example 2: match() fails if pattern is NOT at beginning
result2 = [Link](r'World', 'Hello World')
if result2 is None:
print('No match – World is not at the beginning') # This prints
K
# Example 3: Using groups with match()
pattern = r'(\d{4})-(\d{2})-(\d{2})'
date_str = '2024-11-25 is the exam date'
m = [Link](pattern, date_str)
if m:
print('Full match:', [Link]()) # 2024-11-25
print('Year:', [Link](1)) # 2024
print('Month:', [Link](2)) # 11
print('Day:', [Link](3)) # 25
print('All groups:', [Link]()) # ('2024', '11', '25')
Unit 4 | Regular Expressions & Exception HandlingPage 3
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
OUTPUT
Match found: Hello
Start: 0
End: 5
No match – World is not at the beginning
Full match: 2024-11-25
Year: 2024
Month: 11
Day: 25
All groups: ('2024', '11', '25')
ah
1.7 [Link]() – Complete Example
The [Link]() function scans through the ENTIRE string and returns the first match found anywhere
in the string.
import re
result = [Link](r'World', 'Hello World')
if result:
print('Found:', [Link]())
print('Position:', [Link]())
Sh
# Example 1: search() finds pattern ANYWHERE in string
# Output: Found: World
# Output: Position: (6, 11)
# Example 2: search() with digit pattern
text = 'The student scored 95 marks out of 100'
m = [Link](r'\d+', text)
h
if m:
print('First number found:', [Link]()) # Output: 95
# Example 3: Extract email from text
ris
text2 = 'Contact us at support@[Link] for help'
m2 = [Link](r'[\w.-]+@[\w.-]+\.\w+', text2)
if m2:
print('Email found:', [Link]()) # support@[Link]
1.8 match() vs search() – Key Differences
K
Feature [Link]() [Link]()
Search Scope Only at the BEGINNING of string ANYWHERE in the string
Performance Faster (limited scan) Slightly slower (full scan)
Use Case Validating format of input Finding patterns in long text
Returns None if Pattern not at start Pattern not found anywhere
Example [Link](r'\d+', '42abc') → Match [Link](r'\d+', 'abc42') → Match
Unit 4 | Regular Expressions & Exception HandlingPage 4
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
1.9 [Link]() and [Link]() Examples
import re
# [Link]() – Find ALL occurrences
text = 'My phone is 9876543210 and office is 0221234567'
phones = [Link](r'\d{10}', text)
print('Phone numbers:', phones) # ['9876543210', '0221234567']
# [Link]() – Search and Replace
text2 = 'The cat sat on the mat'
new_text = [Link](r'at', 'AT', text2)
print(new_text) # The cAT sAT on the mAT
ah
# [Link]() with count limit
new_text2 = [Link](r'at', 'AT', text2, count=2)
print(new_text2) # The cAT sAT on the mat (only first 2 replaced)
# [Link]() – Split by pattern
data = 'apple,banana;cherry|date'
parts = [Link](r'[,;|]', data)
print(parts) # ['apple', 'banana', 'cherry', 'date']
EXAM TIPS – re Module Functions Sh
MOST ASKED: Difference between match() and search() – match() = start only, search() =
anywhere.
findall() returns a LIST. finditer() returns an ITERATOR of match objects (memory efficient for
large text).
sub() replaces ALL occurrences unless count= is specified.
h
Always use raw strings: r'pattern' to avoid issues with backslash interpretation.
[Link]() is used when the same pattern is applied multiple times (better performance).
ris
K
Unit 4 | Regular Expressions & Exception HandlingPage 5
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
SECTION 2: REGEX PATTERNS, METACHARACTERS &
MODIFIERS
QUESTION 2 (16 Marks): Explain the Regular Expression patterns and metacharacters available in
Python. Describe quantifiers, anchors, character classes, and flag modifiers with detailed examples.
2.1 Metacharacters in Regex
Metacharacters are special characters that have a specific meaning in regex. They do not match
themselves literally but represent classes of characters or positions.
Metacharacter Meaning & Example
ah
. Matches ANY character except newline. 'h.t' matches 'hat', 'hit', 'hot'
^ Matches START of string. '^Hello' matches if string begins with
'Hello'
$ Matches END of string. 'world$' matches if string ends with 'world'
* Matches 0 or more repetitions. 'ab*' matches 'a', 'ab', 'abb', 'abbb'
+
?
\
|
()
Sh
Matches 1 or more repetitions. 'ab+' matches 'ab', 'abb' but NOT 'a'
Matches 0 or 1 repetition. 'ab?' matches 'a' or 'ab'
Escapes special characters. '\.' matches literal dot
Alternation (OR). 'cat|dog' matches 'cat' OR 'dog'
Groups and captures. '(abc)+' matches 'abc', 'abcabc'
[] Character class. '[aeiou]' matches any vowel
{n} Exactly n repetitions. '\d{3}' matches exactly 3 digits
h
{n,} n or more repetitions. '\d{3,}' matches 3 or more digits
{n,m} Between n and m repetitions. '\d{3,5}' matches 3,4 or 5 digits
ris
2.2 Special Sequences (Escape Characters)
Sequence Description
\d Matches any digit. Equivalent to [0-9]
\D Matches any non-digit. Equivalent to [^0-9]
K
\w Matches any word character (letter, digit, underscore). [A-Za-z0-9_]
\W Matches any non-word character. [^A-Za-z0-9_]
\s Matches any whitespace character (space, tab, newline). [\t\n\r\f]
\S Matches any non-whitespace character
\b Word boundary (outside brackets). Matches position between \w
and \W
\B Non-word boundary
Unit 4 | Regular Expressions & Exception HandlingPage 6
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
\A Matches only at the START of the string (like ^ but stricter)
\Z Matches only at the END of the string (like $ but stricter)
\n Matches newline
\t Matches tab character
2.3 Character Classes
# Character Classes – Matching specific sets of characters
# [abc] – matches a, b, or c
ah
# [a-z] – matches any lowercase letter
# [A-Z] – matches any uppercase letter
# [0-9] – matches any digit (same as \d)
# [a-zA-Z0-9] – matches any alphanumeric character
# [^abc] – matches anything EXCEPT a, b, c (negation using ^)
import re
text = 'Python3 is Great!'
# Find all uppercase letters
print([Link](r'[A-Z]', text))
# Find all alphanumeric characters
print([Link](r'[a-zA-Z0-9]+', text))
Sh # ['P', 'G']
# ['Python3', 'is', 'Great']
# Find anything that is NOT a letter or space
print([Link](r'[^a-zA-Z\s]', text)) # ['3', '!']
h
2.4 Quantifiers – Greedy vs Non-Greedy
By default, quantifiers are GREEDY – they match as many characters as possible.
ris
Adding a ? after a quantifier makes it NON-GREEDY (lazy) – matches as few as possible.
import re
html = '<b>Bold Text</b> and <i>Italic</i>'
# Greedy – matches from first < to LAST >
greedy = [Link](r'<.*>', html)
print('Greedy:', greedy)
K
# Output: ['<b>Bold Text</b> and <i>Italic</i>']
# Non-greedy – matches from < to nearest >
non_greedy = [Link](r'<.*?>', html)
print('Non-greedy:', non_greedy)
# Output: ['<b>', '</b>', '<i>', '</i>']
2.5 Regex Flags/Modifiers
Flag Full Name & Effect
Unit 4 | Regular Expressions & Exception HandlingPage 7
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
re.I or [Link] Case-insensitive matching. 'python' matches 'Python', 'PYTHON'
re.M or [Link] ^ and $ match at start/end of EACH LINE (not just entire string)
re.S or [Link] The dot (.) matches newline \n too (normally it doesn't)
re.X or [Link] Allows whitespace and comments in pattern for readability
re.L or [Link] Character classes affected by locale settings
re.U or [Link] \w, \W, \b, \B use Unicode character properties
import re
ah
# [Link]
result = [Link](r'python', 'Python is pythonic and PYTHON rocks', re.I)
print(result) # ['Python', 'python', 'PYTHON']
# [Link] – ^ and $ match line starts/ends
text = 'First line\nSecond line\nThird line'
starts = [Link](r'^\w+', text, re.M)
print(starts) # ['First', 'Second', 'Third']
# [Link] – dot matches newline
pattern = [Link](r'Start.*End', re.S)
m = [Link]('Start\nsome text\nEnd')
if m: print([Link]()) # Start\nsome text\nEnd
Sh
2.6 Anchors and Boundaries
import re
h
# ^ and $ anchors
print([Link](r'^Hello', 'Hello World')) # Match (at start)
print([Link](r'world$', 'Hello world')) # Match (at end)
ris
print([Link](r'^world$', 'world')) # Match (exact string)
# \b Word boundary
text = 'cat concatenate catfish cats'
# Find exact word 'cat' only
exact = [Link](r'\bcat\b', text)
print(exact) # ['cat']
K
# Without boundary – matches anywhere
all_cat = [Link](r'cat', text)
print(all_cat) # ['cat', 'cat', 'cat', 'cat']
COMMON MISTAKES TO AVOID
1. Forgetting raw strings: Use r'\d+' not '\d+' (backslash issue).
2. Confusing * and +: * allows zero matches, + requires at least one.
3. Greedy vs non-greedy: <.*> grabs too much in HTML. Always use <.*?> for tags.
4. Word boundary \b: Always needed when matching exact whole words.
Unit 4 | Regular Expressions & Exception HandlingPage 8
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
5. Using ^ in character class: [^abc] means NOT a,b,c – not same as anchor ^.
ah
Sh
h
ris
K
Unit 4 | Regular Expressions & Exception HandlingPage 9
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
SECTION 3: REAL-TIME PARSING OF DATA USING REGEX
QUESTION 3 (16 Marks): Explain how Regular Expressions can be used for real-time parsing of data
in Python. Provide programs to extract emails, phone numbers, dates, IP addresses, and other
structured data from unstructured text.
3.1 What is Data Parsing with Regex?
Data Parsing is the process of analysing a sequence of text to extract meaningful structured
information. Regex enables real-time extraction of data patterns such as emails, phone numbers,
dates, IP addresses, and more from raw text.
Real-world applications of Regex-based parsing:
• Log file analysis (web server logs, system logs)
ah
• CSV/text data cleaning and transformation
• Web scraping – extracting data from HTML pages
• Network monitoring – parsing packet data and IP addresses
• Document processing – extracting structured data from reports
3.2 Parsing Email Addresses from Text
import re
text = '''
Sh
Contact: [Link]@[Link] or jane_smith@[Link]
For support: help@[Link] or admin@[Link]
Invalid: not-an-email, @missing, incomplete@
'''
h
# Pattern: local-part @ domain . extension
email_pattern = r'[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}'
emails = [Link](email_pattern, text)
print('Extracted emails:')
ris
for e in emails:
print(' -', e)
OUTPUT
Extracted emails:
- [Link]@[Link]
- jane_smith@[Link]
K
- help@[Link]
- admin@[Link]
3.3 Parsing Phone Numbers
import re
text = 'Reach us at +91-9876543210 or (022) 1234-5678 or 080-44556677'
Unit 4 | Regular Expressions & Exception HandlingPage 10
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
# Indian mobile number pattern
mobile_pattern = r'(\+91[\-\s]?)?[6-9]\d{9}'
mobiles = [Link](mobile_pattern, text)
print('Mobile numbers:', mobiles)
# General phone pattern (includes landline)
phone_pattern = r'[\+\(]?[\d\s\-\(\)]{7,15}'
phones = [Link](phone_pattern, text)
print('All phone patterns:', [[Link]() for p in phones])
3.4 Parsing Dates from Text
ah
import re
log = '''
Server started on 2024-11-25.
Error occurred on 15/08/2024 at 14:30.
Backup done: 25-Dec-2023.
'''
# Pattern 1: YYYY-MM-DD
dates_iso = [Link](r'\d{4}-\d{2}-\d{2}', log)
print('ISO dates:', dates_iso)
# Pattern 2: DD/MM/YYYY
Sh
# ['2024-11-25']
dates_dmy = [Link](r'\d{2}/\d{2}/\d{4}', log)
print('DD/MM/YYYY dates:', dates_dmy) # ['15/08/2024']
# Pattern 3: DD-Mon-YYYY
months = 'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec'
h
dates_text = [Link](r'\d{2}-(?:' + months + r')-\d{4}', log)
print('Text dates:', dates_text) # ['25-Dec-2023']
ris
SECTION 4: PASSWORD VALIDATION USING REGULAR
EXPRESSIONS
QUESTION 4 (16 Marks): Write a Python program to validate a password using Regular Expressions.
The password must have: minimum 8 characters, at least one uppercase, one lowercase, one digit, and
one special character. Explain the regex pattern in detail.
K
4.1 Password Validation Requirements
A strong password must meet these security criteria:
Rule Regex Check
Minimum 8 characters Length check using {8,}
At least one UPPERCASE letter (?=.*[A-Z]) – lookahead
At least one LOWERCASE (?=.*[a-z]) – lookahead
letter
Unit 4 | Regular Expressions & Exception HandlingPage 11
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
At least one DIGIT (0-9) (?=.*\d) or (?=.*[0-9])
At least one SPECIAL character (?=.*[!@#$%^&*(),.?":{}|<>])
No whitespace allowed \S+ or ^\S+$
4.2 Understanding Lookaheads (?=...)
A lookahead (?=...) is a zero-width assertion. It checks if a pattern exists AHEAD of the current position
without consuming characters. This lets us impose multiple independent conditions on the same string.
# Lookahead structure:
# (?=.*[A-Z]) means: somewhere ahead, there is an uppercase letter
ah
# (?=.*[a-z]) means: somewhere ahead, there is a lowercase letter
# (?=.*\d) means: somewhere ahead, there is a digit
# (?=.*[@#$]) means: somewhere ahead, there is a special char
4.3 Complete Password Validation Program
import re
def validate_password(password):
'''
Validates password with the following rules:
- Minimum 8 characters
- At least 1 uppercase letter
- At least 1 lowercase letter
Sh
- At least 1 digit
- At least 1 special character from @#$%^&+=!
- No spaces allowed
h
'''
pattern =
r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=!])(?=\S+$).{8,}$'
ris
if [Link](pattern, password):
return True, 'Password is VALID.'
else:
# Identify exactly what is missing
errors = []
if len(password) < 8:
[Link]('At least 8 characters required')
if not [Link](r'[A-Z]', password):
K
[Link]('At least one uppercase letter required')
if not [Link](r'[a-z]', password):
[Link]('At least one lowercase letter required')
if not [Link](r'\d', password):
[Link]('At least one digit required')
if not [Link](r'[@#$%^&+=!]', password):
[Link]('At least one special character (@#$%^&+=!)
required')
if [Link](r'\s', password):
[Link]('No whitespace characters allowed')
return False, '\n'.join(errors)
# Test cases
Unit 4 | Regular Expressions & Exception HandlingPage 12
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
test_passwords = [
'Pass@123', # Valid
'password', # Missing uppercase, digit, special char
'PASSWORD1@', # Missing lowercase
'Pass 1@a', # Has whitespace
'Py#9', # Too short
'Str0ng@Pass!99', # Valid
]
for pwd in test_passwords:
valid, message = validate_password(pwd)
status = 'VALID' if valid else 'INVALID'
print(f'Password: {pwd:<20} Status: {status}')
if not valid:
ah
print(f' Reason: {message}')
OUTPUT
Password: Pass@123 Status: VALID
Password: password Status: INVALID
Reason: At least one uppercase letter required
At least one digit required
Password: PASSWORD1@ Status: INVALID
Reason: At least one lowercase letter required
Password: Pass 1@a Status: INVALID
Sh
At least one special character (@#$%^&+=!) required
Reason: No whitespace characters allowed
Password: Py#9 Status: INVALID
h
Reason: At least 8 characters required
Password: Str0ng@Pass!99 Status: VALID
ris
4.4 Pattern Breakdown
Pattern Component Meaning
^ Start of string anchor
(?=.*[A-Z]) Lookahead: at least one uppercase letter exists
K
(?=.*[a-z]) Lookahead: at least one lowercase letter exists
(?=.*\d) Lookahead: at least one digit exists
(?=.*[@#$%^&+=!]) Lookahead: at least one special character exists
(?=\S+$) Lookahead: entire string has no whitespace
.{8,} Match any 8 or more characters (main constraint)
$ End of string anchor
5.1 Structure of a Valid Email Address
Unit 4 | Regular Expressions & Exception HandlingPage 13
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
Part Rules & Examples
Local Part (before @) Alphanumeric, dots, underscores, plus, hyphen. e.g., [Link],
alice_123
@ Symbol Mandatory separator. Exactly one @ required.
Domain Name Alphanumeric, hyphens, dots. e.g., gmail, company-name,
[Link]
Top-Level Domain (TLD) 2-6 alphabetic characters. e.g., .com, .org, .in, .[Link]
5.2 Email Validation Program
ah
import re
def validate_email(email):
'''
Validates an email address using regex.
Rules:
- Local part: alphanumeric + . _ % + -
- Exactly one @ symbol
- Domain: alphanumeric + - .
- TLD: 2 to 6 alpha characters
'''
# Comprehensive email regex pattern
Sh
pattern = r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,6}$'
if [Link](pattern, email):
return True
return False
h
def detailed_email_check(email):
'''Checks each part of the email individually.'''
# Check local part
ris
if not [Link](r'^[a-zA-Z0-9._%+\-]+', email):
return False, 'Invalid characters in local part'
# Check exactly one @
if [Link]('@') != 1:
return False, 'Must have exactly one @ symbol'
local, domain = [Link]('@')
# Check domain
if not [Link](r'^[a-zA-Z0-9.\-]+$', domain):
return False, 'Invalid domain'
K
# Check TLD
if not [Link](r'\.[a-zA-Z]{2,6}$', domain):
return False, 'Invalid or missing TLD'
return True, 'Valid email'
# Test cases
test_emails = [
'alice@[Link]', # Valid
'[Link]@[Link]', # Valid
'user+tag@[Link]', # Valid
'invalid-email', # No @ symbol
Unit 4 | Regular Expressions & Exception HandlingPage 14
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
'@[Link]', # Empty local part
'missing@.com', # Domain missing
'double@@[Link]', # Two @ symbols
'test@domain.c', # TLD too short
'[Link]@[Link]',# Valid with subdomain
]
print(f'{'Email':<35} {'Status':<10} {'Detail'}')
print('-' * 65)
for email in test_emails:
valid, msg = detailed_email_check(email)
status = 'VALID' if valid else 'INVALID'
print(f'{email:<35} {status:<10} {msg}')
ah
OUTPUT
Email Status Detail
-----------------------------------------------------------------
alice@[Link] VALID Valid email
[Link]@[Link] VALID Valid email
user+tag@[Link]
invalid-email
@[Link]
missing@.com
double@@[Link]
VALID
Sh Valid email
INVALID Must have exactly one @ symbol
INVALID Invalid characters in local part
INVALID Invalid domain
INVALID Must have exactly one @ symbol
test@domain.c INVALID Invalid or missing TLD
[Link]@[Link] VALID Valid email
h
5.3 Email Pattern Explanation
ris
Pattern Component Explanation
^ Start of string
[a-zA-Z0-9._%+\-]+ Local part: one or more alphanumeric/special chars
@ Literal @ character
[a-zA-Z0-9.\-]+ Domain: one or more alphanumeric/dot/hyphen
K
\. Literal dot before TLD
[a-zA-Z]{2,6} TLD: 2 to 6 alphabetic characters only
$ End of string
6.1 Structure of a URL
A URL (Uniform Resource Locator) has the following components:
[Link]
Unit 4 | Regular Expressions & Exception HandlingPage 15
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
| | | | | | |
scheme subdomain domain port path query fragment
URL Component Description & Examples
Scheme/Protocol http, https, ftp (required)
Subdomain www (optional, e.g., [Link])
Domain Name example, google, python (required)
TLD .com, .org, .net, .in (required)
Port :8080, :443, :3000 (optional)
ah
Path /page/[Link] (optional)
Query String ?key=value&key2=val (optional)
Fragment #section (optional)
6.2 URL Validation Program
import re
def validate_url(url):
'''
Validates URLs with the following components:
- Scheme: http or https (required)
Sh
- Domain: www optional, alphanumeric + hyphens
- TLD: 2-6 alpha characters
- Port: optional (:8080)
h
- Path: optional (/path/to/resource)
- Query: optional (?key=value)
- Fragment: optional (#anchor)
'''
ris
pattern = (
r'^(https?://))' # scheme: http or https
r'(([a-zA-Z0-9\-]+\.)+)' # domain parts
r'[a-zA-Z]{2,6}' # TLD
r'(:\d+)?' # optional port
r'(/[\w\-._~:/?#\[\]@!$&\'()*+,;=%]*)?' # path/query/fragment
r'$'
)
K
return bool([Link](pattern, url))
# Cleaner version of the pattern for exam:
def validate_url_simple(url):
pattern = r'^https?://[\w\-]+(\.[\w\-]+)+(/[\w\-./?%&=]*)?$'
return bool([Link](pattern, url))
# Test Cases
test_urls = [
'[Link]
'[Link]
Unit 4 | Regular Expressions & Exception HandlingPage 16
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
'[Link]
'[Link]
'[Link] # Invalid (not http/https)
'[Link]', # Invalid (no scheme)
'[Link] # Invalid (empty domain)
'[Link] # Valid
'not a url at all', # Invalid
]
for url in test_urls:
result = validate_url_simple(url)
status = 'VALID ' if result else 'INVALID'
print(f'{status} | {url}')
ah
OUTPUT
VALID | [Link]
VALID | [Link]
VALID | [Link]
VALID | [Link]
INVALID | [Link]
INVALID | [Link]
INVALID | [Link]
VALID | [Link]
INVALID | not a url at all
Sh
h
ris
K
Unit 4 | Regular Expressions & Exception HandlingPage 17
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
7.1 What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instructions. When Python encounters an error, it raises an exception. If the exception is not handled,
the program terminates abruptly with an error message.
Types of Errors in Python:
Error Type Description & Example
Syntax Error Grammatical errors in code. Detected at compile time. e.g., missing
colon after if
Runtime Error (Exception) Errors that occur during execution. e.g., dividing by zero, file not
found
ah
Logical Error Program runs but gives wrong output. Cannot be caught by Python
automatically
7.2 Exception Hierarchy in Python
BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
├── ArithmeticError
│
│
├── ZeroDivisionError
├── OverflowError
Sh
│ └── FloatingPointError
├── LookupError
│ ├── IndexError
h
│ └── KeyError
├── ValueError
├── TypeError
├── IOError / OSError
ris
│ └── FileNotFoundError
├── NameError
├── AttributeError
├── ImportError
└── RuntimeError
K
7.3 The try-except-else-finally Block
Python provides a structured way to handle exceptions using four keywords:
Keyword Purpose
try Block of code that might raise an exception. Always required.
except Block executed when a specific (or any) exception is raised.
else Block executed ONLY IF no exception was raised in try block.
finally Block ALWAYS executed, regardless of exception (cleanup code).
Unit 4 | Regular Expressions & Exception HandlingPage 18
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
# Syntax:
try:
# code that may raise an exception
risky_statement
except ExceptionType1 as e:
# handle ExceptionType1
print('Error:', e)
except ExceptionType2 as e:
# handle ExceptionType2
print('Error:', e)
except Exception as e:
# catch any other exception (general handler)
print('Unexpected error:', e)
else:
ah
# runs only if NO exception was raised
print('Code ran successfully')
finally:
# always runs – use for cleanup (close file, release resources)
print('Finally block executed')
def safe_division(a, b):
try:
result = a / b
except ZeroDivisionError as e:
Sh
7.4 Complete Exception Handling Program with All Blocks
print(f'Error: Cannot divide by zero – {e}')
return None
except TypeError as e:
print(f'Error: Invalid input type – {e}')
return None
h
else:
print(f'Division successful: {a} / {b} = {result}')
return result
finally:
ris
print('Execution of safe_division() complete.\n')
# Test cases
safe_division(10, 2) # Normal case
safe_division(10, 0) # ZeroDivisionError
safe_division('a', 2) # TypeError
OUTPUT
K
Division successful: 10 / 2 = 5.0
Execution of safe_division() complete.
Error: Cannot divide by zero – division by zero
Execution of safe_division() complete.
Error: Invalid input type – unsupported operand type(s) for /: 'str' and 'int'
Execution of safe_division() complete.
Unit 4 | Regular Expressions & Exception HandlingPage 19
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
7.5 Multiple except Clauses
def process_file_data(filename, index):
try:
with open(filename, 'r') as f:
lines = [Link]()
data = lines[index]
value = int([Link]())
result = 100 / value
print(f'Result: {result}')
except FileNotFoundError:
print(f'Error: File "{filename}" not found.')
except IndexError:
print(f'Error: Index {index} is out of range.')
except ValueError:
ah
print('Error: Could not convert data to integer.')
except ZeroDivisionError:
print('Error: Value in file is zero, cannot divide.')
except Exception as e:
print(f'Unexpected error: {type(e).__name__}: {e}')
finally:
print('File operation attempt complete.')
Sh
7.6 The raise Statement – Manually Raising Exceptions
The raise keyword is used to manually trigger an exception in Python.
def set_age(age):
if not isinstance(age, int):
raise TypeError('Age must be an integer')
if age < 0 or age > 150:
raise ValueError(f'Age {age} is out of valid range (0-150)')
h
print(f'Age set to: {age}')
# Test
try:
ris
set_age(25) # Valid
set_age(-5) # Raises ValueError
except ValueError as e:
print(f'ValueError: {e}')
try:
set_age('old') # Raises TypeError
except TypeError as e:
K
print(f'TypeError: {e}')
OUTPUT
Age set to: 25
ValueError: Age -5 is out of valid range (0-150)
TypeError: Age must be an integer
7.7 Custom Exception Classes
Python allows creation of user-defined exceptions by inheriting from the Exception class.
Unit 4 | Regular Expressions & Exception HandlingPage 20
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
# Defining Custom Exceptions
class InvalidAgeError(Exception):
def __init__(self, age, message='Age is not valid'):
[Link] = age
[Link] = message
super().__init__([Link])
def __str__(self):
return f'{[Link]} -> Provided age: {[Link]}'
class BankError(Exception):
pass
ah
class InsufficientFundsError(BankError):
def __init__(self, balance, amount):
[Link] = balance
[Link] = amount
super().__init__(f'Cannot withdraw {amount}. Balance: {balance}')
# Using Custom Exceptions
def withdraw(balance, amount):
try:
if amount > balance:
Sh
raise InsufficientFundsError(balance, amount)
return balance - amount
new_balance = withdraw(500, 800)
except InsufficientFundsError as e:
print(f'Bank Error: {e}')
h
try:
raise InvalidAgeError(-3)
except InvalidAgeError as e:
print(f'Custom Exception: {e}')
ris
OUTPUT
Bank Error: Cannot withdraw 800. Balance: 500
Custom Exception: Age is not valid -> Provided age: -3
K
Unit 4 | Regular Expressions & Exception HandlingPage 21
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
QUICK REVISION SUMMARY NOTES
Regex Functions – At a Glance
Function Returns / Behaviour
[Link](p, s) Match at START → match object or None
[Link](p, s) Match ANYWHERE → match object or None
[Link](p, s) All matches → list of strings
[Link](p, s) All matches → iterator of match objects
[Link](p, r, s) Replace all matches → new string
ah
[Link](p, r, s) Replace all + count → (new_string, count)
[Link](p, s) Split by pattern → list
[Link](p) Compile pattern → regex object (reuse)
[Link](p, s) Match ENTIRE string → match object or None
Regex Cheat Sheet – Important Patterns
Pattern
\d
Matches
Any digit
Sh Example
\d{3} → '123'
\D Non-digit \D+ → 'abc'
\w Word char (letter/digit/_) \w+ → 'hello_3'
h
\s Whitespace \s+ → ' '
. Any char (not newline) .+ → 'abc123'
ris
^ Start of string ^Hello → 'Hello world'
$ End of string world$ → 'Hello world'
* 0 or more ab* → 'a', 'ab', 'abb'
+ 1 or more ab+ → 'ab', 'abb'
? 0 or 1 ab? → 'a', 'ab'
K
{n,m} n to m repetitions \d{3,5} → '123' to '12345'
[abc] Any of a,b,c [aeiou] → vowels
[^abc] Not a,b,c [^0-9] → non-digit
(abc) Group + capture (\d+) captures digits
a|b a OR b cat|dog
(?=...) Lookahead (?=.*[A-Z]) has uppercase
(?!...) Negative lookahead (?!.*[0-9]) no digits
Unit 4 | Regular Expressions & Exception HandlingPage 22
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
Exception Handling Quick Revision Table
Exception Cause Example
ZeroDivisionError Dividing a number by zero 10 / 0
TypeError Operation on incompatible types 'a' + 3
ValueError Right type, wrong value int('abc')
IndexError List index out of range lst[10] on len-3 list
KeyError Dictionary key not found d['missing_key']
FileNotFoundError File doesn't exist open('[Link]')
NameError Variable not defined print(undefined_var)
ah
AttributeError Object has no such attribute 'str'.nonexistent()
ImportError Module not found import nonexistent
OverflowError Result too large for numeric type [Link](1000)
RecursionError Maximum recursion depth Infinite recursive call
exceeded
StopIteration
Sh
Iterator has no more items next() on exhausted iterator
h
ris
K
Unit 4 | Regular Expressions & Exception HandlingPage 23
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
IMPORTANT REGEX PATTERNS CHEAT SHEET
Validation Patterns – Copy & Use in Exam
# Email: r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,6}$'
# URL: r'^https?://[\w\-]+(\.[\w\-]+)+(/[\w\-./?%&=]*)?$'
# Password: r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=!])(?=\S+$).{8,}$'
# Indian Mobile: r'^[6-9]\d{9}$'
ah
# IPv4: r'^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$'
# Date YYYY-MM-DD: r'^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$'
# Username: r'^[a-zA-Z0-9_]{5,20}$'
# Zip Code (India): r'^[1-9][0-9]{5}$'
# HTML Tag: r'<[a-zA-Z]+[^>]*>'
Sh
Top 10 EXAM POINTS to Remember
1. [Link]() checks only from the BEGINNING; [Link]() checks the ENTIRE string.
h
2. [Link]() returns a LIST; [Link]() returns an ITERATOR (memory efficient).
3. Always use RAW strings: r'\d+' – prevents Python from interpreting backslashes.
4. Lookaheads (?=...) are ZERO WIDTH – they don't consume characters.
ris
5. * is greedy by default. Make it lazy with *?
6. [Link]() compiles pattern once – use when pattern is reused many times.
7. finally block ALWAYS runs – even if exception is raised or not.
8. Use 'except Exception as e' as a CATCH-ALL but only for debugging.
9. Custom exceptions must inherit from Exception class (or its subclass).
10. raise re-raises the same exception if used alone inside except block.
K
Unit 4 | Regular Expressions & Exception HandlingPage 24
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
SECTION 9: ADDITIONAL PATTERN FINDING PROGRAMS
Program 1: Find All Words Starting with a Vowel
import re
text = 'An eagle is an amazing animal that eats insects often'
words = [Link](r'\b[aeiouAEIOU]\w*', text)
print('Words starting with vowel:', words)
# Output: ['An', 'eagle', 'is', 'an', 'amazing', 'animal', 'eats',
'insects', 'often']
ah
Program 2: Extract All Numbers (including decimals)
import re
text = 'Pi is 3.14159, e is 2.71828, and 42 is the answer'
numbers = [Link](r'\d+\.?\d*', text)
print('Numbers found:', numbers)
# Output: ['3.14159', '2.71828', '42']
Program 3: Replace All Whitespace with Single Space
import re
messy = 'This has multiple spaces
clean = [Link](r'\s+', ' ', messy).strip()
Sh
and\ttabs'
print(clean) # This has multiple spaces and tabs
h
Program 4: Validate and Extract Credit Card Numbers
import re
ris
def validate_credit_card(number):
# Remove spaces/dashes
number = [Link](r'[\s\-]', '', number)
# Check: 16 digits
if [Link](r'^\d{16}$', number):
return True, number
return False, None
K
cards = ['4111-1111-1111-1111', '1234 5678 9012 3456', '123456789',
'abcd1234efgh5678']
for card in cards:
valid, num = validate_credit_card(card)
print(f'{card}: {"VALID – " + num if valid else "INVALID"}')
Program 5: Named Groups in Regex
import re
Unit 4 | Regular Expressions & Exception HandlingPage 25
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
# Named groups make code more readable
pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
date_str = '2024-11-25'
m = [Link](pattern, date_str)
if m:
print('Year:', [Link]('year')) # 2024
print('Month:', [Link]('month')) # 11
print('Day:', [Link]('day')) # 25
print('Dict:', [Link]())
# {'year': '2024', 'month': '11', 'day': '25'}
ah
Sh
h
ris
K
Unit 4 | Regular Expressions & Exception HandlingPage 26
Python Programming – Unit 4: Regular Expressions & Exception HandlingExam Preparation Notes
FINAL EXAM STRATEGY & MEMORY AIDS
HOW TO WRITE A 16-MARK REGEX ANSWER
Step 1 (1 mark) – Write a crisp INTRODUCTION (1-2 sentences defining the concept).
Step 2 (2 marks) – Give THEORY with definition, syntax, and parameters table.
Step 3 (3 marks) – Explain the PATTERN or METHOD with component-by-component
breakdown.
Step 4 (5 marks) – Write a COMPLETE PYTHON PROGRAM (well-commented, multiple
test cases).
Step 5 (2 marks) – Show the EXPECTED OUTPUT clearly.
Step 6 (2 marks) – Write ADVANTAGES, USE CASES, and a brief CONCLUSION.
ah
Step 7 (1 mark) – Mention COMMON MISTAKES or edge cases to impress the examiner.
MNEMONIC – re Module Functions: 'MS FAX SUB COMP'
M – match() → Beginning only
S – search() → Anywhere in string
F – findall() → Returns List
A – finditer() → Returns Iterator
X – fullmatch() → Entire string
SUB – sub() → Substitute/Replace
COMP – compile() → Compile for speed
Sh
MNEMONIC – Exception Handling: 'TEEF'
h
T – try → Try the risky code
E – except → Except (handle) the error
E – else → Else (success path)
ris
F – finally → Finally (cleanup, always runs)
IMPORTANT – What Examiners Look For
Correct syntax for re functions (parameters, return values).
Proper use of raw strings r'...' in all regex patterns.
K
Programs must include: import re, test cases, and print statements.
For exception handling: always show try-except-finally together.
For custom exceptions: show class definition + raise + catch.
Pattern explanations (breaking down each component of the regex).
At least 3-4 diverse test cases per validation program.
End of Exam Preparation Notes – Unit 4: Regular Expressions & Exception Handling
Prepared with expertise for University Examination Excellence
Unit 4 | Regular Expressions & Exception HandlingPage 27