Regular Expressions Basics
Regular expressions (regex) are patterns for matching text. Python's re module lets you search, validate, extract, and replace text efficiently.
20 min•By Priygop Team•Updated 2026
Regex Basics
Regex Basics
import re
text = "Contact us at support@email.com or visit https://example.com"
# re.search() — find first match
match = re.search(r'\w+@\w+\.\w+', text)
if match:
print(f"Email found: {match.group()}")
# re.findall() — find all matches
emails = re.findall(r'[\w.]+@[\w.]+', text)
print(f"All emails: {emails}")
# re.sub() — replace
cleaned = re.sub(r'\d+', 'X', "Order 123 shipped on 2024-01-15")
print(cleaned)
# Common patterns
phone = "My number is 9876543210"
print(re.findall(r'\d{10}', phone)) # ['9876543210']
# Validate email
def is_valid_email(email):
pattern = r'^[\w.]+@[\w]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
print(is_valid_email("alice@gmail.com")) # True
print(is_valid_email("invalid@")) # False
# Extract data
log = "2024-01-15 ERROR Server crashed"
parts = re.match(r'(\d{4}-\d{2}-\d{2}) (\w+) (.*)', log)
if parts:
print(f"Date: {parts.group(1)}")
print(f"Level: {parts.group(2)}")
print(f"Message: {parts.group(3)}")Tip
Tip
Use raw strings r'pattern' for regex to avoid double-escaping backslashes. re.compile() for patterns used multiple times.
Diagram
Loading diagram…
Quantifiers, character classes, anchors, and flags
Common Mistake
Warning
re.match() only matches at the START of the string. Use re.search() to find a pattern anywhere in the string.
Practice Task
Note
(1) Validate an email with regex. (2) Extract all phone numbers from text. (3) Replace all digits with X. (4) Parse a log line with groups.