Concept Explanation
Have you ever tried to find every email address in a 500-page document? Or tried to verify if a user's password contains at least one number and one symbol? Doing this with simple string methods like find() would be a nightmare.
This is where RegEx (Regular Expressions) comes in. RegEx is a special mini-language used to describe search patterns in text. Think of it as "Ctrl+F on steroids." It allows you to find, extract, and replace complex patterns of text with just a few lines of code.
The re Module
Python provides the built-in re module to work with regular expressions. In Python, we almost always use Raw Strings (r"pattern") for RegEx to prevent backslashes from being interpreted as escape characters.
Syntax or Core Structure
Special Characters (Metacharacters)
- . (Dot): Matches any single character except a newline.
- ^ (Caret): Matches the start of the string.
- $ (Dollar): Matches the end of the string.
- * (Star): Zero or more occurrences.
- + (Plus): One or more occurrences.
- ? (Question): Zero or one occurrence.
- {n,m}: Exactly between n and m occurrences.
- []: A set of characters (e.g.,
[a-z]matches any lowercase letter). - |: Either or (e.g.,
cat|dog).
Common Sequences
- \d: Any digit (0-9).
- \w: Any word character (letters, numbers, underscores).
- \s: Any whitespace (space, tab, newline).
Code Example #1 (Basic)
Using findall() to extract all occurrences and search() to find the first one.
import re
text = "The rain in Spain falls mainly on the plain."
# 1. findall: Get all matches in a list
matches = re.findall(r"ai", text)
print(f"Found 'ai' {len(matches)} times: {matches}")
# 2. search: Find the first match and get its position
match_obj = re.search(r"Spain", text)
if match_obj:
print(f"Found 'Spain' at index: {match_obj.start()}")
Code Example #2 (Intermediate)
Using sub() to replace text and split() to break strings apart.
import re
# 1. sub: Replace all spaces with underscores
data = "User Name 123"
clean_data = re.sub(r"\s", "_", data)
print(clean_data) # User_Name_123
# 2. split: Split string by any non-word character
sentence = "Python is fun, right? Yes!"
words = re.split(r"\W+", sentence)
print(words) # ['Python', 'is', 'fun', 'right', 'Yes', '']
Real World Example
Email Validator: A classic use case for RegEx is checking if an input follows the "name@domain.com" format.
import re
def is_valid_email(email):
# Pattern: [chars] @ [chars] . [2-4 chars]
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
if re.match(pattern, email):
return True
return False
emails = ["test@gmail.com", "invalid-email@", "hello.world@company.org"]
for e in emails:
status = "Valid" if is_valid_email(e) else "Invalid"
print(f"{e}: {status}")
Common Mistakes
- Forgetting the 'r' prefix: Using
"\d"instead ofr"\d"can lead to errors because Python might try to escape the backslash itself. - Match vs Search:
re.match()only checks the beginning of a string. If the pattern is in the middle, it returnsNone. Usere.search()for looking anywhere. - Greedy Matching: Metacharacters like
*and+are "greedy"—they match as much text as possible. For example,<.*>on<b>bold</b>will match the whole thing, not just the tags. Use*?or+?for "lazy" matching.
Best Practices
- Keep it Simple: If a standard string method like
startswith()orinworks, use that instead. RegEx is slower and harder to read. - Test Patterns First: Use tools like Regex101 to visualize your patterns before putting them in code.
- Comment your RegEx: If you write a long, complex pattern, add a comment explaining what each part does.
Practice Exercises
- Phone Finder: Write a pattern to find all phone numbers in the format
123-456-7890. - Vowel Counter: Use
re.findall()to count how many vowels are in a given sentence. - Space Cleaner: Write a script that replaces multiple spaces in a row with a single space.