Regex cheatsheet
Javascript Regex/Regular Expression cheatsheet
About Regex cheatsheet
A compact reference for JavaScript regular expressions: character classes, anchors, quantifiers, groups and backreferences, lookaround, flags and the escape sequences, with the meaning of each token.
When you would use it
- Recalling the exact syntax of a lookbehind, a named group or a lazy quantifier while writing a pattern.
- Checking which flags exist and what the u, s and y flags do.
- Teaching regular expressions with a one-page overview.
How to use it
- Find the section for the construct you need.
- Read the token and its meaning, then try it in the Regex Tester tool.
- Use your browser's search (Ctrl+F) for a specific token.
Things worth knowing
- This sheet describes the JavaScript flavour. Named groups are (?<name>...), and \d, \w and \s match ASCII only unless the u flag and Unicode property escapes such as \p{L} are used.
- Quantifiers are greedy by default; add ? (as in .*?) to make them lazy. Nested quantifiers such as (a+)+ can cause catastrophic backtracking on some inputs.
- Lookbehind ((?<=...) and (?<!...)) is supported in all current browsers but was missing in Safari before 16.4; check your target environment.
- Inside a character class most metacharacters lose their meaning, so [.] matches a literal dot, while - and ] need escaping or careful placement.
Frequently asked questions
- What is the difference between .* and .*?
- .* is greedy and takes as much as possible, then backs off; .*? is lazy and takes as little as possible. On <b>a</b><b>b</b>, <b>.*</b> matches everything while <b>.*?</b> matches the first tag pair only.
- Why does \d not match Arabic-Indic or other digits?
- In JavaScript \d is always [0-9]. To match digits in other scripts use \p{Nd} with the u flag.