Advertisement
❮ Previous: Python Strings & String Formatting Next: Python Lists & List Comprehensions ❯

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")

Advertisement

2. Metacharacters & Syntax Reference

Regular expressions rely on special characters (metacharacters) to define search patterns:

Common Special Sequences

(Note: Always use raw strings (prefixing your pattern with r, like r"\d+") to prevent Python from interpreting backslashes as escape characters.)


Advertisement

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']

Try this code ❯

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

Try this code ❯

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

Try this code ❯


Advertisement

4. Useful Regex Flags

You can modify how regex patterns behave by passing flags as arguments (e.g., re.IGNORECASE):

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!")

Try this code ❯

❮ Previous: Python Strings & String Formatting Next: Python Lists & List Comprehensions ❯
Advertisement