Regex Cheatsheet

This cheatsheet provides a comprehensive and practical reference for regular expressions. It covers character classes, anchors, quantifiers, groups, common patterns, command combos, and more. Use it to boost your productivity in pattern matching and text processing.

Character Classes

.
Any character except newline
\d
Digit (0-9)
\D
Non-digit
\w
Word character (alphanumeric or _)
\W
Non-word character
\s
Whitespace (space, tab, etc.)
\S
Non-whitespace
[abc]
a, b, or c
[^abc]
Any character except a, b, or c
[a-z]
Any lowercase letter
[A-Z]
Any uppercase letter
[0-9]
Any digit

Anchors

^
Start of string or line
$
End of string or line
\b
Word boundary
\B
Non-word boundary
^abc$
Exact match 'abc'

Quantifiers

*
0 or more
+
1 or more
?
0 or 1
{n}
Exactly n times
{n,}
At least n times
{n,m}
Between n and m times
*?
Non-greedy 0 or more
+?
Non-greedy 1 or more

Groups & References

(abc)
Capture group
(?:abc)
Non-capturing group
(?<name>abc)
Named capturing group
\1, \2, ...
Backreference to group 1, 2, ...
(?=abc)
Positive lookahead
(?!abc)
Negative lookahead
(?<=abc)
Positive lookbehind
(?<!abc)
Negative lookbehind

Common Patterns

^\d{4}-\d{2}-\d{2}$
Date (YYYY-MM-DD)
^\d{3}-\d{3}-\d{4}$
US phone number (123-456-7890)
^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
Email address
https?://[w.-]+
URL (http/https)
^#[0-9A-Fa-f]{6}$
Hex color (#RRGGBB)
\b\w{8,}\b
Word with 8 or more characters
\b([A-Za-z]+) \1\b
Duplicate consecutive words
\b[1-9][0-9]*\b
Positive integer
\b0[xX][0-9A-Fa-f]+\b
Hexadecimal number

Command Combos

/foo|bar/
Match 'foo' or 'bar'
/^.{8,}$/
Match lines with 8 or more characters
/(cat|dog|fish)/i
Match 'cat', 'dog', or 'fish' (case-insensitive)
s/(d{3})-(d{2})-(d{4})/XXX-XX-$3/
Mask SSN in text (replace first 5 digits)
grep -E 'error|fail' app.log
Find lines containing 'error' or 'fail' in a log file
sed -n '/pattern/p' file.txt
Print lines matching pattern in file.txt
awk '/pattern/ {print $0}' file.txt
Print lines matching pattern using awk
cat file.txt | grep -E 'foo|bar' | sort | uniq
Find unique lines containing 'foo' or 'bar'

Categories

  • Character Classes

    Match specific types or ranges of characters, such as digits, letters, or whitespace.

  • Anchors

    Match positions in the string, such as the start, end, or word boundaries.

  • Quantifiers

    Specify how many times a pattern should occur.

  • Groups & References

    Group patterns, capture matches, and use backreferences or lookarounds.

  • Common Patterns

    Ready-to-use regexes for emails, dates, URLs, numbers, and more.

  • Command Combos

    Powerful multi-step workflows and advanced usage patterns for real-world scenarios.

Features

  • Quick search functionality
  • Organized by categories
  • Clear pattern descriptions
  • Common and advanced use cases covered
  • Easy to copy patterns
  • Responsive design
  • Perfect for quick reference