Python Regular Expressions (Regex) Tutorial | Pattern Matching & Data Validation
Modern software applications process enormous amounts of text every day. Whether validating email addresses, checking passwords, extracting phone numbers, searching log files, processing customer information, or cleaning datasets for Artificial Intelligence, developers rely on Regular Expressions (Regex) for powerful pattern matching.
Python provides the built-in re module that allows developers to search, validate, replace, split, and extract text efficiently using regular expressions.
Regex is widely used in Web Development, Artificial Intelligence, Machine Learning, Data Analytics, Cybersecurity, Web Scraping, Automation, and Backend Development because it simplifies complex text-processing tasks.
In this lesson, you’ll learn how Regular Expressions work, understand regex syntax, use the most important functions in Python’s re module, validate user input, extract information from text, and solve real-world programming problems.
By the end of this lesson, you’ll be able to confidently use Regex to process and validate textual data in professional Python applications.
Learning Objectives
After completing this lesson, you will be able to:
- Understand Regular Expressions.
- Use Python’s
remodule. - Search patterns in text.
- Validate user input.
- Extract information from strings.
- Replace and split text using Regex.
- Write efficient Regex patterns.
- Apply Regex in real-world applications.
Topics Covered
- Introduction to Regex
- The
reModule - Regex Metacharacters
- Search Functions
- Match Functions
- Find All
- Replace Text
- Split Text
- Validation Patterns
- Real-World Applications
Detailed Lesson Content
Introduction to Regular Expressions
Imagine you’re developing a Student Registration Portal.
Every student enters:
- Email Address
- Mobile Number
- Password
- Date of Birth
Instead of checking every character manually, Python allows you to validate all these inputs using Regular Expressions (Regex).
Regex is a sequence of characters that defines a search pattern.
It helps developers:
- Validate input
- Search text
- Extract information
- Replace text
- Clean datasets
What is Regex?
Regular Expression (Regex) is a pattern used to match text.
Example
Suppose we want to find:
Python
inside
Learn Python Programming
Regex quickly finds the matching word.
Importing the re Module
Python provides the re module.
import re
This module contains all Regex functions.
re.search()
Searches for the first occurrence.
Example
import re
text = "Learn Python Programming"
result = re.search("Python", text)
print(result)
Output
<re.Match object>
Checking if a match exists
if result:
print("Found")
Output
Found
re.match()
Matches only at the beginning of the string.
Example
import re
text = "Python Programming"
print(re.match("Python", text))
Output
<re.Match object>
Example
print(re.match("Programming", text))
Output
None
re.findall()
Returns all matching values.
Example
import re
text = "Python Java Python AI Python"
print(re.findall("Python", text))
Output
['Python','Python','Python']
re.finditer()
Returns an iterator of all matches.
import re
text = "Python AI Python"
for match in re.finditer("Python", text):
print(match.start())
Output
0
10
re.sub()
Replaces matching text.
Example
import re
text = "Python Programming"
result = re.sub("Python","Java",text)
print(result)
Output
Java Programming
re.split()
Splits text using a pattern.
Example
import re
text = "Python,Java,AI,React"
print(re.split(",",text))
Output
['Python','Java','AI','React']
Common Regex Metacharacters
| Symbol | Meaning |
|---|---|
. |
Any character |
^ |
Beginning of string |
$ |
End of string |
* |
Zero or more occurrences |
+ |
One or more occurrences |
? |
Optional character |
[] |
Character set |
() |
Grouping |
\d |
Digit |
\D |
Non-digit |
\w |
Word character |
\W |
Non-word character |
\s |
Whitespace |
\S |
Non-whitespace |
Email Validation
Example
import re
email = "student@gmail.com"
pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
if re.match(pattern,email):
print("Valid Email")
else:
print("Invalid Email")
Mobile Number Validation
Example
import re
mobile = "9876543210"
pattern = r'^[6-9][0-9]{9}$'
print(bool(re.match(pattern,mobile)))
Output
True
Password Validation
import re
password = "Python@123"
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=]).{8,}$'
print(bool(re.match(pattern,password)))
Extracting Numbers
Example
import re
text = "Order ID: 45231"
print(re.findall(r"\d+",text))
Output
['45231']
Extracting Email Addresses
import re
text = "Contact: admin@gmail.com"
emails = re.findall(
r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}',
text
)
print(emails)
Real-World Example 1: Registration Form
import re
email = input("Email: ")
if re.match(
r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$',
email
):
print("Registration Successful")
else:
print("Invalid Email")
Real-World Example 2: OTP Extraction
import re
message = "Your OTP is 846291"
otp = re.findall(r"\d+",message)
print(otp)
Real-World Example 3: Log File Analysis
import re
log = "ERROR 404"
error = re.search(r"\d+",log)
print(error.group())
Output
404
Real-World Example 4: AI Data Cleaning
import re
text = "Python!!! AI@@@"
clean = re.sub(r"[^A-Za-z ]","",text)
print(clean)
Output
Python AI
Common Mistakes
Forgetting Raw Strings
Incorrect
"\d+"
Correct
r"\d+"
Using match() Instead of search()
Remember:
match()checks only the beginning.search()checks the entire string.
Writing Overly Complex Patterns
Break complex patterns into smaller parts and test them gradually.
Best Practices
- Use raw strings (
r"") for Regex patterns. - Keep patterns simple and readable.
- Test Regex thoroughly with different inputs.
- Validate all user input before processing.
- Use named groups for complex patterns.
- Avoid unnecessary backtracking in large datasets.



