Regex Cheat Sheet

Cheet says: Master patterns, master data!

Basic Patterns

. Any single character \d Digit [0-9] \D Non-digit \w Word char [a-zA-Z0-9_] \W Non-word char \s Whitespace \S Non-whitespace

Anchors

^ Start of line/string $ End of line/string \b Word boundary \B Not word boundary

Quantifiers

* 0 or more + 1 or more ? 0 or 1 {3} Exactly 3 {3,} 3 or more {3,5} Between 3 and 5 *? Lazy (non-greedy) * +? Lazy +

Character Classes

[abc] a, b, or c [^abc] Not a, b, or c [a-z] Lowercase letter [A-Z] Uppercase letter [0-9] Digit [a-zA-Z] Any letter

Groups & Captures

(abc) Capture group (?:abc) Non-capturing group (?x) Named group \1 Backreference to group 1

Lookahead & Lookbehind

(?=abc) Positive lookahead (?!abc) Negative lookahead (?<=abc) Positive lookbehind (?

Common Patterns


Email (simple)

[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}

IP Address

\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b

URL

https?://[^\s]+

Phone (US)

\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}

Date (YYYY-MM-DD)

\d{4}-\d{2}-\d{2}

Time (HH:MM)

\d{2}:\d{2}

Hex color

#[0-9A-Fa-f]{6}

Username

^[a-zA-Z0-9_]{3,16}$

Strong password

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Grep Examples


grep -E 'pattern' file         # Extended regex
grep -P 'pattern' file         # Perl regex
grep -i 'pattern' file         # Case insensitive
grep -v 'pattern' file         # Invert match
grep -o 'pattern' file         # Only matching part
grep -c 'pattern' file         # Count matches

Find IPs in log

grep -oE '\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b' access.log

Find emails

grep -oE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' file

Sed Examples


sed 's/old/new/' file          # Replace first
sed 's/old/new/g' file         # Replace all
sed -E 's/([0-9]+)/[\1]/g'     # Use groups
sed '/pattern/d' file          # Delete matching lines
sed -n '/pattern/p' file       # Print matching only

Flags

i Case insensitive g Global (all matches) m Multiline mode s Dotall (. matches newline) x Extended (ignore whitespace)

Testing Tools


Online

regex101.com # Best for testing regexr.com # Good visualizer

CLI

echo "test" | grep -E 'pattern' [[ "test" =~ pattern ]] && echo "match"