Python Advanced
Python Regular Expressions
Regular expressions let you search, match, and replace text using powerful patterns. Python's built-in re module gives you everything you need to work with them.
Importing re
Regular expression support comes from the re module, which is part of Python's standard library, so there is nothing to install. Patterns are written as strings, often as raw strings using an r prefix to avoid escaping backslashes.
import re
pattern = r"\d+" # one or more digitsmatch(), search() and findall()
match() checks only the beginning of a string, search() scans the whole string for the first match, and findall() returns a list of every match found. All three take the pattern first, then the text.
import re
text = "Order 12 has 5 items and costs 499 rupees"
print(re.match(r"\d+", text))
print(re.search(r"\d+", text).group())
print(re.findall(r"\d+", text))None
12
['12', '5', '499']sub() — Search and Replace
The sub() function replaces every match of a pattern with a replacement string, similar to find-and-replace but powered by patterns instead of exact text.
import re
text = "Call me at 9876543210"
masked = re.sub(r"\d{10}", "**********", text)
print(masked)Common Metacharacters
Regex patterns are built from special characters called metacharacters. Combining them lets you describe very flexible search rules in a single short pattern.
| Pattern | Meaning |
|---|---|
| . | Any character except newline |
| \d | Any digit (0-9) |
| \w | Any word character (letter, digit, _) |
| \s | Any whitespace character |
| + | One or more of the previous |
| * | Zero or more of the previous |
| ? | Zero or one of the previous |
| ^ | Start of string |
| $ | End of string |
| [abc] | Any one of a, b, or c |
Always use raw strings (prefix with r) for regex patterns so backslashes like \d and \s are passed to re exactly as written.
Compile patterns you reuse often with re.compile() for cleaner code and slightly better performance in loops.
Frequently Asked Questions
What is the difference between re.match() and re.search()?+
re.match() only checks for a match at the very start of the string and returns None otherwise. re.search() scans the entire string and returns the first match found anywhere in it.
Why should I use raw strings for regex patterns?+
Raw strings (prefixed with r) stop Python from interpreting backslashes as escape sequences, so patterns like \d or \s reach the re module exactly as you typed them instead of being misread.
How do I extract all matches instead of just the first one?+
Use re.findall(pattern, text), which returns a list of every non-overlapping match in the string, or re.finditer() if you also need position information for each match.
