Python Expressions
Python's built-in re module provides powerful pattern-matching and string-manipulation capabilities using regular expressions (regex). Whether you are validating user inputs, cleaning messy text datasets, or scraping data, regex is an essential tool in every Python developer's toolkit.
1. Importing and Core Functions
To use regular expressions in Python, you first need to import the module:
import re
The re module provides several primary functions for working with patterns:
| Function | Description | Example |
|---|---|---|
re.search(pattern, string) |
Scans through string looking for the first location where the regex pattern produces a match. |
re.search(r"cat", "The cat sat.") |
re.match(pattern, string) |
Determines if the regex matches at the beginning of the string. | re.match(r"The", "The cat sat.") |
re.findall(pattern, string) |
Finds all non-overlapping matches of the pattern in the string and returns them as a list of strings. | re.findall(r"\d+", "Order 42, item 7") |
re.finditer(pattern, string) |
Returns an iterator yielding match objects for all non-overlapping matches. | for m in re.finditer(r"\d+", text): ... |
re.sub(pattern, repl, string) |
Replaces occurrences of the pattern in string with the replacement string repl. |
re.sub(r"\s+", "-", "hello world") |
re.compile(pattern) |
Compiles a regular expression pattern into a regex object, which is more efficient for repeated use. | pattern = re.compile(r"a.b") |
2. Metacharacters & Syntax Reference
Regular expressions rely on special characters (metacharacters) to define search patterns:
^(Caret): Matches the start of a string (e.g.,^Hellomatches strings starting with "Hello").$(Dollar): Matches the end of a string (e.g.,world$matches strings ending with "world")..(Period): Matches any character except a newline.*(Asterisk): Matches 0 or more repetitions of the preceding character.+(Plus): Matches 1 or more repetitions of the preceding character.?(Question Mark): Matches 0 or 1 repetition (makes the preceding element optional, or performs non-greedy matching).[](Character Set): Matches any single character inside the brackets (e.g.,[aeiou]matches any vowel).|(Alternation / OR): Matches either the expression before or after the pipe (e.g.,cat|dog).()(Group): Captures and groups parts of a match.
Common Special Sequences
\d: Matches any digit (equivalent to[0-9]).\D: Matches any non-digit.\w: Matches any alphanumeric character and underscore ([a-zA-Z0-9_]).\W: Matches any non-alphanumeric character.\s: Matches any whitespace character (spaces, tabs, newlines).\S: Matches any non-whitespace character.
(Note: Always use raw strings (prefixing your pattern with r, like r"\d+") to prevent Python from interpreting backslashes as escape characters.)
3. Practical Code Examples
Example 1: Extracting Phone Numbers
import re
text = "Call me at 555-123-4567 or at 555-987-6543 today."
# Pattern for XXX-XXX-XXXX format
pattern = r"\d{3}-\d{3}-\d{4}"
phones = re.findall(pattern, text)
print(phones)
# Output: ['555-123-4567', '555-987-6543']
Example 2: Email Validation
import re
def is_valid_email(email):
# Basic email regex pattern
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
return bool(re.match(pattern, email))
print(is_valid_email("user.name@example.co.uk")) # Output: True
print(is_valid_email("invalid-email.com")) # Output: False
Example 3: Using Match Objects and Groups
When you need more than just the matched text (like capturing specific sections), use search() or match() and inspect the Match Object:
import re
text = "My order number is #9876-AB."
pattern = r"#(\d+)-([A-Z]+)"
match = re.search(pattern, text)
if match:
print("Full Match:", match.group(0)) # #9876-AB
print("Order ID:", match.group(1)) # 9876
print("Category Code:", match.group(2)) # AB
4. Useful Regex Flags
You can modify how regex patterns behave by passing flags as arguments (e.g., re.IGNORECASE):
re.IGNORECASE(orre.I): Performs case-insensitive matching.re.MULTILINE(orre.M): Makes^and$match the start and end of each line rather than the whole string.re.DOTALL(orre.S): Makes the.metacharacter match all characters, including the newline (\n).
import re
text = "Hello\nWORLD"
# Without flags, 'world' lowercase won't match uppercase text across newline
match = re.search(r"hello.*world", text, re.IGNORECASE | re.DOTALL)
if match:
print("Matched successfully!")