Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

Regex Cheatsheet

Regular expressions (regex) are patterns used for string matching and manipulation. Here’s a quick reference guide for common regex syntax:

Basics

  • .: Matches any character except a newline.
  • ^: Matches the start of a string or line.
  • $: Matches the end of a string or line.

Character Classes

  • [abc]: Matches any character 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.
  • [a-zA-Z0-9]: Matches any alphanumeric character.
  • \d: Matches any digit (short for [0-9]).
  • \w: Matches any word character (alphanumeric + underscore).
  • \s: Matches any whitespace character (space, tab, newline).

Quantifiers

  • *: Matches the preceding element zero or more times.
  • +: Matches the preceding element one or more times.
  • ?: Matches the preceding element zero or one time.
  • {n}: Matches the preceding element exactly n times.
  • {n,}: Matches the preceding element n or more times.
  • {n,m}: Matches the preceding element between n and m times.

Groups and Alternation

  • (abc): Matches the group abc and captures it.
  • (?:abc): Matches the group abc without capturing it.
  • a|b: Matches either a or b.

Anchors

  • \b: Matches a word boundary.
  • \B: Matches a position that is not a word boundary.
  • (?=...): Positive lookahead assertion.
  • (?!...): Negative lookahead assertion.

Escaping Special Characters

  • \\: Escapes a special character (e.g., \\. matches a literal period).

Flags (Depends on Language)

  • i: Case-insensitive matching.
  • g: Global match (find all occurrences).
  • m: Multiline mode (^ and $ match the start/end of each line).
  • s: Dot matches all, including newlines.
  • u: Treat the pattern and input as UTF-16 or UTF-32.
  • x: Ignore whitespace and allow comments.

Examples

  • /\d{3}-\d{2}-\d{4}/: Matches a standard US social security number.
  • /^[A-Za-z]+$/: Matches a string containing only letters.
  • /https?:\/\/(www\.)?\w+\.\w+/: Matches URLs starting with http:// or https://.
  • /(\d+)\s?-\s?\1/: Matches repeated numbers separated by a hyphen.
  • ^(\/[^\/?]+)(\/[^\/?]+)?(\/[^\/?]+)?: Match all text up to the 3rd β€˜/’ in a URL
  • ^[a-z][a-z0-9+\-.]*://([a-z0-9\-._~%!$&'()*+,;=]+@)?([a-z0-9\-._~%]+|\[[a-z0-9\-._~%!$&'()*+,;=:]+\]): extract hostname from URL
  • ^https?:\/\/(.*)(\/[^\/?]+)(\/[^\/?]+)?(\/[^\/?]+)?: Match protocol (http/s), hostname, and path (3 forward slashes)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet