Regular Expressions (Regex) in Python (re Module)
A Regular Expression (RegEx) is a special sequence of characters that defines a search pattern. It is used to search, match, extract, validate, or replace specific patterns inside text strings (such as checking if an email address or 10-digit mobile number is valid).
To work with Regular Expressions, Python provides the built-in re module:
import re
1. Core Functions in the re Module
The re module provides 5 main functions for pattern matching:
Top Functions in Python's re Module
1. re.findall(pattern, text)
Returns a list containing all non-overlapping matches in the string.
2. re.search(pattern, text)
Scans the entire string and returns a Match object for the first match (or
None).3. re.match(pattern, text)
Checks for a match ONLY at the very beginning (index 0) of the string.
4. re.sub(pat, repl, text)
Replaces (substitutes) all occurrences of the pattern with
repl.5. re.split(pattern, text)
Splits the string into a list wherever the pattern matches.
Example Demonstrating re Functions:
import re
text = "BCA Sem 3 has 45 students and Sem 5 has 60 students."
# 1. findall() -> Extract all numbers (\d+) from the text
numbers = re.findall(r"\d+", text)
print("Numbers found:", numbers) # Output: ['3', '45', '5', '60']
# 2. search() -> Find the first occurrence of a number
match_obj = re.search(r"\d+", text)
if match_obj:
print("First number:", match_obj.group()) # Output: 3
# 3. sub() -> Replace all numbers with 'XX'
masked = re.sub(r"\d+", "XX", text)
print("Masked text:", masked)
# Output: BCA Sem XX has XX students and Sem XX has XX students.
Difference between
re.match()andre.search():
re.match()checks only at the start of the string.re.search()searches anywhere inside the entire string.
2. RegEx Meta-Characters & Special Sequences
To build powerful search patterns, RegEx uses Meta-characters and Special Sequences (always prefix regex strings with r"..." for Raw Strings):
A. Important Meta-Characters:
| Meta-character | Meaning | Example Pattern | Matches |
|---|---|---|---|
[ ] |
A set/range of characters | [a-z], [0-9] |
Any lowercase letter or any single digit |
^ |
Starts with | ^Hello |
Any string that starts with "Hello" |
. |
Any single character (except newline) | c.t |
"cat", "cot", "cut" |
* |
0 or more occurrences | ab* |
"a", "ab", "abb", "abbb" |
+ |
1 or more occurrences | ab+ |
"ab", "abb" (but NOT "a") |
? |
0 or 1 occurrence (Optional) | colou?r |
Both "color" and "colour" |
{n} |
Exactly n occurrences |
\d{10} |
Exactly 10 digits |
| |
Either / Or | BCA|MCA |
Matches either "BCA" or "MCA" |
B. Important Special Sequences:
| Sequence | Meaning | Equivalent To |
|---|---|---|
\d |
Matches any Digit (0 to 9) |
[0-9] |
\D |
Matches any Non-Digit character | [^0-9] |
\w |
Matches any alphanumeric Word character (letters, digits, _) |
[a-zA-Z0-9_] |
\s |
Matches any Whitespace character (space, tab, newline) | [ \t\n] |
3. Practical Exam Case Studies (Validation Programs)
Case Study 1: Validate an Indian 10-Digit Mobile Number
An Indian mobile number must start with 6, 7, 8, or 9 followed by 9 more digits (total 10 digits):
- Pattern:
r"^[6-9]\d{9}\Z"
import re
def validate_mobile(phone):
pattern = r"^[6-9]\d{9}\Z"
if re.match(pattern, phone):
print(f"{phone} is a VALID Indian Mobile Number.")
else:
print(f"{phone} is INVALID!")
validate_mobile("9876543210") # VALID
validate_mobile("1234567890") # INVALID (starts with 1)
Case Study 2: Extract All Email Addresses from a Paragraph
import re
paragraph = "Contact us at [email protected] or [email protected] for help."
# Pattern for email: username @ domain . extension
email_pattern = r"[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = re.findall(email_pattern, paragraph)
print("Extracted Emails:", emails)
# Output: ['[email protected]', '[email protected]']