CodeNebula
Python📦Standard Libraryintermediate

`re` — Regular Expressions

Python · Standard Library · Run with python3

Explanation

The `re` module provides Perl-compatible regular expressions. Key functions: `re.match` (anchored at start), `re.search` (anywhere in string), `re.findall` (all matches), `re.finditer` (iterator of match objects), `re.sub` (replace), `re.split`. Compile patterns with `re.compile()` for reuse. Flags: `re.IGNORECASE`, `re.MULTILINE`, `re.DOTALL`. Groups: `()` for capture, `(?:...)` for non-capture, `(?P<name>...)` for named groups.

Real-World Scenario

Parsing log lines: `re.compile(r'(?P<ip>\d+\.\d+\.\d+\.\d+) .* "(?P<method>GET|POST) (?P<path>/\S*)"')` extracts IP, method, and path from Apache access logs — far more readable than string splitting. ```python import re LOG_PATTERN = re.compile( r"(?P<ip>\d+\.\d+\.\d+\.\d+)\s+" r"\[(?P<date>[^\]]+)\]\s+" r'"(?P<method>\w+)\s+(?P<path>\S+)"' r"\s+(?P<status>\d+)" ) log_line = '192.168.1.1 [15/Mar/2024:10:30:00] "GET /api/users" 200' if m := LOG_PATTERN.search(log_line): print(f"IP: {m.group('ip')}") print(f"Path: {m.group('path')}") print(f"Status: {m.group('status')}") # Substitution with backreferences text = "John Smith, Jane Doe" swapped = re.sub(r"(\w+) (\w+)", r"\2, \1", text) print(swapped) # Smith, John, Doe, Jane ```

Quick Snippet

snippet.py
import re

LOG_PATTERN = re.compile(
    r"(?P<ip>\d+\.\d+\.\d+\.\d+)\s+"
    r"\[(?P<date>[^\]]+)\]\s+"
    r'"(?P<method>\w+)\s+(?P<path>\S+)"'
    r"\s+(?P<status>\d+)"
)

log_line = '192.168.1.1 [15/Mar/2024:10:30:00] "GET /api/users" 200'
if m := LOG_PATTERN.search(log_line):
    print(f"IP: {m.group('ip')}")
    print(f"Path: {m.group('path')}")
    print(f"Status: {m.group('status')}")

# Substitution with backreferences
text = "John Smith, Jane Doe"
swapped = re.sub(r"(\w+) (\w+)", r"\2, \1", text)
print(swapped)  # Smith, John, Doe, Jane

Full Example

regex_basics.py
# Compile: python3 regex_basics.py
# Output:
# IP: 192.168.1.1
# Path: /api/users
# Status: 200
# Smith, John, Doe, Jane

import re

LOG_PATTERN = re.compile(
    r"(?P<ip>\d+\.\d+\.\d+\.\d+)\s+"
    r"\[(?P<date>[^\]]+)\]\s+"
    r'"(?P<method>\w+)\s+(?P<path>\S+)"'
    r"\s+(?P<status>\d+)"
)

log_line = '192.168.1.1 [15/Mar/2024:10:30:00] "GET /api/users" 200'
if m := LOG_PATTERN.search(log_line):
    print(f"IP: {m.group('ip')}")
    print(f"Path: {m.group('path')}")
    print(f"Status: {m.group('status')}")

text = "John Smith, Jane Doe"
swapped = re.sub(r"(\w+) (\w+)", r"\2, \1", text)
print(swapped)

# findall
emails = "Contact alice@example.com or bob@test.org for info"
found = re.findall(r"[\w.+-]+@[\w-]+\.\w+", emails)
print(found)

# split
csv = "one,two,,three,four"
parts = re.split(r",+", csv)
print(parts)
Run command
python3 regex_basics.py