Regex Basics
Overview
Regular Expressions (Regex) are an incredibly powerful, language-agnostic tool used to search, extract, and manipulate strings based on complex patterns rather than exact character matches. Python supports regex via the built-in re module. While regex syntax can look like cryptic gibberish initially, mastering it allows you to validate emails, extract phone numbers, or sanitize massive text documents with a single line of code instead of writing massive if/else loops.
Syntax
import re
text = "Contact support at help@company.com or sales at sales@company.com."
# re.search() finds the FIRST match in the string
match = re.search(r'w+@w+.com', text)
if match:
print("Found email:", match.group())
# Found email: help@company.com
# re.findall() returns a list of ALL matches
all_emails = re.findall(r'w+@w+.com', text)
print(all_emails)
# ['help@company.com', 'sales@company.com']
# Replacing patterns
redacted = re.sub(r'w+@w+.com', '[REDACTED]', text)Common Pitfalls
- Not using 'raw strings' (
r"pattern") for your regex rules. Regular strings interpret backslashes (like\nfor newline). Raw strings pass the backslashes directly to the regex engine. - Using
re.match()when you actually wantre.search().match()ONLY searches at the very beginning of the string. If the pattern is in the middle of the string,match()fails.
Interview Questions
re.search() and re.findall()?search() scans the string and returns a Match Object representing the first occurrence it finds. findall() scans the entire string and returns a standard list containing all matched strings.
Real-World Example
Validating that a password meets strict security requirements (minimum length, contains numbers and letters).
import re
def is_strong_password(pwd):
# Regex breakdown:
# (?=.*[A-Za-z]) -> Must contain at least one letter
# (?=.*d) -> Must contain at least one digit
# .{8,} -> Must be at least 8 characters long
pattern = r'^(?=.*[A-Za-z])(?=.*d).{8,}$'
return bool(re.match(pattern, pwd))Check Your Knowledge
Test your understanding of Regex Basics with these quick questions.