iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Examples

A small gallery of regex patterns that come up in real codebases: email-ish, phone (E.164), date, URL, IPv4/IPv6, log line, and JWT shape. Each comes with the pattern, what it matches, what it deliberately does NOT match, and the "better tool" if a regex is the wrong call.

Seven regex patterns with caveats

EXAMPLE
# 1) Email — "good enough for a form" check (validate by SENDING a token!)
EMAIL = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
# Matches:    alice@example.com, bob+filter@sub.example.co.uk
# Misses:     extreme corner cases of RFC 5321 (which YOU do not want to parse)
# Better:     ALWAYS verify via email-to-the-address; regex is only a typo check

# 2) Phone — E.164 (the canonical international format)
PHONE = r'^\+[1-9]\d{1,14}$'
# Matches:    +61412345678, +14155552671
# Misses:     spaces, hyphens, parens (normalise before validating)
# Better:     google's libphonenumber for parsing + region-aware validation

# 3) Date — ISO 8601 yyyy-mm-dd
DATE = r'^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$'
# Matches:    2026-06-18
# Misses:     2026-02-30  (regex cannot count days in February). Then parse with the language's date library.
# Better:     parse with datetime.fromisoformat or chrono / luxon — handles leap years properly

# 4) URL — protocol + host minimal check
URL = r'^https?://[^\s/$.?#].[^\s]*$'
# Matches:    http://example.com/path?q=1
# Misses:     deliberately rejects URLs without a TLD (file://, javascript:)
# Better:     new URL(s) in JS; urllib.parse.urlparse in Python — strict + structured

# 5) IP addresses
IPV4 = r'^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$'
IPV6 = r'^([\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$'   # NOT compressed form
# Matches:    192.168.0.1   2001:0db8:85a3:0000:0000:8a2e:0370:7334
# Misses:     IPv6 compressed (::1), IPv4-mapped IPv6
# Better:     ipaddress.ip_address(s) in Python; net.IP in Go

# 6) Log line — Apache combined format with named groups
APACHE = r'^(?P<ip>\d{1,3}(?:\.\d{1,3}){3}) \S+ \S+ \[(?P<ts>[^\]]+)\] \"(?P<method>[A-Z]+) (?P<path>[^ ]+) HTTP/[\d.]+\" (?P<status>\d{3}) (?P<bytes>\d+|-)'
# Use re.compile + finditer for stream processing; do NOT recompile inside the loop

# 7) JWT shape — three base64url chunks separated by dots
JWT = r'^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$'
# Matches:    the structural shape of a JWT
# Misses:     anything about signature validity — you MUST verify cryptographically
# Better:     jwt.decode(token, key, algorithms=['RS256']) — never trust the shape alone

# ===== When regex is the WRONG tool =====
# - Parsing HTML / XML       -> use a proper parser (lxml, html5parser)
# - Parsing JSON / YAML      -> json / yaml libraries; never grep them
# - Parsing CSV with quoting -> csv.reader handles commas inside quoted fields
# - Anything 'almost a regex but with one nested rule' -> a real parser
# - Validating credentials/  -> NEVER regex; verify cryptographically

Why it matters

For "is this email valid?" use a permissive regex on the front-end AND verify by sending a token to the address. Strict email regexes reject valid addresses (the RFC allows almost everything in the local part) and waste your time on edge cases the user never types. Verification via the email itself is the only reliable check.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Pattern catalogue: identifiers, ISO dates, currency, slugs, semver, IPs.
Try it Yourself »

Discussion

Loading…