๐ฏ Lesson Objective
To understand and apply Regular Expressions (RegEx) in Python for searching, validating, and manipulating text patterns efficiently.
๐งฉ 1. What Are Regular Expressions?
Regular Expressions (RegEx) are special patterns used to match strings or parts of strings.
Python provides the re module to work with these expressions.
โ Importing RegEx Module:
import re
โ๏ธ 2. Common RegEx Functions
| Function | Description |
|---|---|
re.search() | Finds the first match in a string |
re.findall() | Returns all matches as a list |
re.match() | Checks if string starts with the pattern |
re.split() | Splits string by the matched pattern |
re.sub() | Replaces pattern with a new string |
๐ 3. Basic Examples
Example 1 โ search()
import re
text = "My phone number is 9876543210"
pattern = r"\d{10}"
match = re.search(pattern, text)
print(match.group())
Output:
9876543210
Example 2 โ findall()
text = "Emails: user1@gmail.com, user2@yahoo.com"
emails = re.findall(r'\S+@\S+', text)
print(emails)
Output:
['user1@gmail.com', 'user2@yahoo.com']
Example 3 โ match()
text = "Python is powerful"
result = re.match(r"Python", text)
print(result)
Output:
<re.Match object; span=(0, 6), match='Python'>
Example 4 โ split()
text = "apple,banana;orange grape"
words = re.split(r'[;,\s]+', text)
print(words)
Output:
['apple', 'banana', 'orange', 'grape']
Example 5 โ sub()
text = "My number is 9876543210"
new_text = re.sub(r'\d+', '**********', text)
print(new_text)
Output:
My number is **********
๐งฑ 4. Common RegEx Patterns
| Pattern | Meaning | Example Match |
|---|---|---|
\d | Digit (0โ9) | 3 |
\D | Non-digit | A |
\w | Word character (aโz, 0โ9, _) | a |
\W | Non-word character | @ |
\s | Whitespace | (space, tab) |
^ | Start of string | ^Python |
$ | End of string | end$ |
. | Any character (except newline) | c.t โ cat, cot |
* | 0 or more repetitions | lo*l โ ll, lol, loool |
+ | 1 or more repetitions | go+ โ go, goo, gooo |
{n} | Exactly n times | \d{4} โ 2025 |
| ` | ` | OR condition |
[] | Character set | [A-Z] matches AโZ |
๐ง 5. Real-Life Use Cases
- Validate email, phone number, or passwords
- Extract data from text (e.g., IDs, numbers, dates)
- Find or replace text in logs or documents
- Split structured text (CSV, JSON strings)
๐ 6. Real-Life Example โ Email Validation
import re
email = "sameer123@gmail.com"
pattern = r'^[a-zA-Z0-9._]+@[a-z]+\.[a-z]+$'
if re.match(pattern, email):
print("Valid email address!")
else:
print("Invalid email address!")
Output:
Valid email address!
๐ฌ 7. Password Strength Validation
password = "Pa$$word123"
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
if re.match(pattern, password):
print("Strong password!")
else:
print("Weak password!")
Output:
Strong password!

Leave a Reply