Regex Cheat Sheet

This comprehensive regex cheat sheet includes common patterns, quantifiers, anchors, boundaries, and more.

Basic Regex Syntax

Regular expressions (regex) are patterns used to match character combinations in strings. Here are the basics:

  • . - Matches any character except a newline
  • \d - Matches any digit (0-9)
  • \w - Matches any word character (a-z, A-Z, 0-9, _)
  • \s - Matches any whitespace character
  • [abc] - Matches any character in the set (a, b, or c)
  • [^abc] - Matches any character not in the set (not a, b, or c)
  • {n} - Matches exactly n occurrences
  • * - Matches 0 or more occurrences
  • + - Matches 1 or more occurrences
  • ^ - Anchors to the start of a string
  • $ - Anchors to the end of a string

Regex Quantifiers

Quantifiers specify how many times a pattern should occur:

  • * - Matches 0 or more times
  • + - Matches 1 or more times
  • ? - Matches 0 or 1 time (optional)
  • {n} - Matches exactly n times
  • {n,} - Matches n or more times
  • {n,m} - Matches between n and m times

Regex Anchors

Anchors ensure that your pattern matches specific positions in the string:

  • ^ - Matches the beginning of a string
  • $ - Matches the end of a string
  • \b - Word boundary
  • \B - Not a word boundary

Regex Groups and Lookahead

Groups and lookaheads are useful for capturing parts of matches or checking for conditions without consuming characters:

  • (abc) - Capturing group for abc
  • (?:abc) - Non-capturing group
  • (?=abc) - Positive lookahead (asserts that abc is ahead)
  • (?!abc) - Negative lookahead (asserts that abc is not ahead)

Character Classes

Character classes allow you to match specific sets of characters:

  • [abc] - Matches "a", "b", or "c"
  • [^abc] - Matches any character except "a", "b", or "c"
  • [a-z] - Matches any lowercase letter
  • [A-Z] - Matches any uppercase letter
  • [0-9] - Matches any digit

Common Regex Patterns

Pattern Explanation Example
^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$ Email validation Matches user@example.com
^\+?\d{1,4}[-.\s]?\(?\d{1,4}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9} Phone number validation Matches +123 (456) 789-0123
^(http|https):\/\/[^\s]+$ URL validation Matches https://www.example.com
^[0-9]{5}(?:-[0-9]{4})?$ US ZIP code (5 or 9 digits) Matches 12345 or 12345-6789
\b\d{1,3}(,\d{3})*(\.\d+)?\b Number with commas Matches 1,234.56