How to test a regular expression
- Type your pattern into the regular expression field, without the surrounding slashes.
- Tick the flags you need, for example g to find all matches and i to ignore case.
- Paste sample text into the test string box. Matches are highlighted as you type, and syntax errors are shown immediately.
- Check the match details for each match's position and its numbered and named capture groups.
- Enter a replacement such as
$1or$<name>to preview the result ofString.replace.
How JavaScript regex matching works
JavaScript regular expressions follow the ECMAScript specification and use a backtracking engine. The engine tries the pattern at each position in the text; when part of the pattern fails, it goes back and tries the next alternative or a different number of repetitions. Flags change this behaviour: g continues after each match, m makes ^ and $ match at line breaks, s lets . match newlines, u enables full Unicode handling and \p{...} property escapes, y anchors each match at the current position, and d records the start and end index of every group.
A pattern that can match an empty string, such as a*, matches zero characters at many positions. This tester advances past empty matches so the loop always ends, and stops listing after 1000 matches.
Regex cheat sheet
| Syntax | Meaning |
|---|---|
. | Any character except line breaks (add the s flag to include them) |
\d \w \s | Digit, word character [A-Za-z0-9_], whitespace |
\D \W \S | The opposite of each of the above |
[abc] [^abc] [a-z] | Any of, none of, range |
^ $ | Start and end of input (of each line with the m flag) |
\b | Word boundary |
* + ? | 0 or more, 1 or more, 0 or 1 |
{3} {2,} {2,5} | Exactly 3, at least 2, between 2 and 5 |
*? +? | Lazy versions: match as few characters as possible |
(abc) | Capture group, available as $1 |
(?<name>abc) | Named capture group, available as $<name> |
(?:abc) | Group without capturing |
a|b | Either a or b |
(?=x) (?!x) | Lookahead: followed by x, not followed by x |
(?<=x) (?<!x) | Lookbehind: preceded by x, not preceded by x |
\1 \k<name> | Backreference to a group inside the pattern |
\. \* \( | Escape a special character to match it literally |