Python 24-Day CourseDay 16pythonintermediate
Python 24-Day Course - Day 16: Regular Expressions
· 2 min read
Day 16: Regular Expressions
Basic Usage
import re
text = "Phone: 010-1234-5678, Email: user@example.com"
# Pattern search
phone = re.search(r"\d{3}-\d{4}-\d{4}", text)
if phone:
print(phone.group()) # 010-1234-5678
Key Pattern Syntax
| Pattern | Description | Example |
|---|
\d | Digit | \d+ -> “123” |
\w | Letter/digit/underscore | \w+ -> “hello_1” |
\s | Whitespace | \s+ -> ” “ |
. | Any character | a.c -> “abc” |
* | 0 or more | ab*c -> “ac”, “abc” |
+ | 1 or more | ab+c -> “abc” |
? | 0 or 1 | colou?r -> “color” |
{n,m} | n to m repetitions | \d{2,4} -> “12”, “1234” |
[] | Character class | [aeiou] -> vowels |
^ / $ | Start / End | ^Hello |
() | Group capture | (\d+)-(\d+) |
Key Functions
text = "3 apples, 5 bananas, 12 cherries"
# findall: find all matches
numbers = re.findall(r"\d+", text)
print(numbers) # ['3', '5', '12']
# sub: substitution
cleaned = re.sub(r"\d+", "N", text)
print(cleaned) # N apples, N bananas, N cherries
# split: splitting
parts = re.split(r",\s*", text)
print(parts) # ['3 apples', '5 bananas', '12 cherries']
Group Capture
pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
match = re.search(pattern, "Today is 2026-04-20")
if match:
print(match.group("year")) # 2026
print(match.group("month")) # 04
print(match.group("day")) # 20
Email Validation Example
def is_valid_email(email):
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return bool(re.match(pattern, email))
print(is_valid_email("user@example.com")) # True
print(is_valid_email("invalid-email")) # False
Today’s Exercises
- Write a regular expression that extracts all URLs from a text.
- Validate password strength (at least 8 characters with uppercase, lowercase, digits, and special characters).
- Create a function using regular expressions to strip HTML tags.
Was this article helpful?
Thanks for your feedback!