←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Regular Expressions (Regex) in Python (re Module)

Study material and explanations for Unit 4

Regular Expressions (Regex) in Python (re Module)

To validate a six-digit PIN code field, use a whole-string match with [0-9]{6}. Searching for the same pattern inside a longer sentence answers a different question. The pattern checks format, not whether the postal code exists.

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:

Search looks for a match anywhere and match tests from the start. Fullmatch checks the whole input, while sub and split transform or divide text using 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() and re.search():

  • re.match() checks only at the start of the string.
  • re.search() searches anywhere inside the entire string.

View diagram · Top Functions in Python’s re Module


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 support@campusnotes.in or admin123@gmail.com 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: ['support@campusnotes.in', 'admin123@gmail.com']