Regex cheatsheet

What is a Regex Memo?

Regular expressions are a compact language for matching text patterns, used for validation, search and replace, log parsing and data extraction. The syntax is dense and easy to forget. This cheat sheet summarises the JavaScript regex syntax with short examples, so you can find the token you need quickly.

Character classes

  • . any character except a line break (with the s flag, including line breaks).
  • \d digit, \w word character (letter, digit, underscore), \s whitespace. Uppercase versions negate them.
  • [abc] one of a, b or c; [^abc] anything else; [a-z] a range.

Quantifiers

  • * zero or more, + one or more, ? zero or one.
  • {3} exactly 3, {2,5} between 2 and 5, {2,} 2 or more.
  • Add ? to make a quantifier lazy: .*? matches as little as possible.

Anchors and boundaries

  • ^ start and $ end of string (or line with the m flag).
  • \b word boundary: \bcat\b matches cat but not category.

Groups and lookaround

  • (abc) capturing group, (?:abc) non-capturing, (?<year>\d{4}) named group.
  • (?=x) lookahead, (?!x) negative lookahead.
  • (?<=x) lookbehind, (?<!x) negative lookbehind.
  • \1 backreference to group 1.

Flags

g global, i case-insensitive, m multiline, s dot matches newline, u Unicode, y sticky, d match indices.

Examples

  • ISO date: ^\d{4}-\d{2}-\d{2}$
  • Hex colour: ^#?([0-9a-f]{3}|[0-9a-f]{6})$ with the i flag.
  • Price without currency: (?<=\$)\d+(\.\d{2})?

Frequently Asked Questions

What is the difference between greedy and lazy quantifiers?

Greedy quantifiers such as .* match as much as possible. Lazy ones such as .*? match as little as possible.

What does a lookahead do?

It checks that some pattern follows the current position without including it in the match.

Does JavaScript support lookbehind?

Yes. All modern browsers and Node.js support lookbehind assertions.

What does the u flag do?

It enables full Unicode matching, so characters outside the basic plane, such as emojis, are treated as single characters.