</> hexnook

Regex cheat sheet: the patterns you'll actually use

This isn't exhaustive — it's the subset of regex syntax that covers the vast majority of real-world patterns. Everything below works with JavaScript's native RegExp engine, the same one hexnook's regex tester runs against.

Anchors

  • ^ — start of string (or line, with the m flag)
  • $ — end of string (or line, with the m flag)
  • \b — word boundary

Character classes

  • . — any character except a newline (unless the s flag is set)
  • \d / \D — digit / non-digit
  • \w / \W — word character (letters, digits, underscore) / non-word
  • \s / \S — whitespace / non-whitespace
  • [abc] — any one of a, b, or c
  • [^abc] — any character except a, b, or c
  • [a-z] — any character in the range a to z

Quantifiers

  • * — zero or more
  • + — one or more
  • ? — zero or one (also marks a quantifier as "lazy" when placed after one)
  • {n} — exactly n times
  • {n,} — n or more times
  • {n,m} — between n and m times

Groups

  • (...) — capturing group (shows up in the match's group list)
  • (?:...) — non-capturing group (groups for precedence only, doesn't appear in results)
  • (?<name>...) — named capturing group
  • | — alternation ("or") — usually used inside a group, e.g. (cat|dog)

A few real patterns

  • Simple email match: [\w.+-]+@[\w-]+\.[\w.-]+ (production email validation is notoriously harder than it looks — this covers the common case, not the full RFC).
  • Digits only: ^\d+$
  • Whitespace-trimming: ^\s+|\s+$ with the g flag
  • Extract hex color: #[0-9a-fA-F]{6}
Try the Regex Tester →