Regular Expressions: A Practical Cheat Sheet

Regular expressions have a reputation for being write-only code — powerful, but unreadable the moment you come back to it six months later. A solid grasp of the core building blocks makes them far less mysterious, and genuinely useful across every language and text editor you’ll ever use.

The Building Blocks

.        any character except newline
\d       digit           \D  non-digit
\w       word character  \W  non-word character
\s       whitespace      \S  non-whitespace
^        start of string (or line, in multiline mode)
$        end of string (or line, in multiline mode)
*        0 or more       +   1 or more       ?   0 or 1
{n,m}    between n and m repetitions
[abc]    any one of a, b, c
[^abc]   any character except a, b, c
(...)    capturing group
(?:...)  non-capturing group
|        alternation (OR)

Real Patterns You’ll Actually Use

import re

# Extract an email address
email_pattern = r'[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}'
re.findall(email_pattern, "Contact us at hello@example.com or admin@site.org")

# Validate a simple date format YYYY-MM-DD
date_pattern = r'^\d{4}-\d{2}-\d{2}$'
bool(re.match(date_pattern, "2025-09-08"))

# Named groups for structured extraction
log_pattern = r'(?P<ip>\d+\.\d+\.\d+\.\d+) - - \[(?P<timestamp>[^\]]+)\]'
match = re.search(log_pattern, '192.168.1.1 - - [08/Sep/2025:22:20:14] "GET / HTTP/1.1" 200')
match.group('ip'), match.group('timestamp')

# Replace with a backreference
re.sub(r'(\w+)@(\w+)\.com', r'\1 [at] \2 [dot] com', 'contact me at john@example.com')

When Not to Reach for Regex

Regex is great for pattern matching in flat text, but a terrible tool for parsing structured formats like HTML, JSON, or XML — those have nesting rules regex fundamentally can’t express correctly. Use a real parser for those; save regex for flat, line-oriented text like logs, config values, and simple validation.