How to test a regular expression
- Type your pattern between the slashes, without adding slashes yourself, and tick the flags you need. g finds every match instead of only the first.
- Paste your text into Test text. Matches are highlighted as you type and Matches lists each one with its position and groups.
- To try a substitution, type into Replace with. Use $1, $2 or $<name> to insert a group and $& for the whole match.
Regex cheat sheet
| Token | Meaning |
|---|---|
\d |
A digit, 0 to 9 |
\w |
A letter, digit or underscore (A to Z only, so é doesn’t count) |
\s |
Whitespace: a space, tab or line break |
. |
Any character except a line break, or any at all with the s flag |
^ and $ |
Start and end of the text, or of each line with the m flag |
* + ? |
Repeat 0 or more times, 1 or more times, or make optional |
{n,m} |
Repeat n to m times. {3} is exactly 3 and {3,} is 3 or more |
[abc] [^abc] [a-z] |
One character from the set, not in the set, or in the range |
(...) |
Capturing group, inserted with $1, $2 in the replacement |
(?:...) |
Group without capturing |
(?<name>...) |
Named group, inserted with $<name> |
a|b |
a or b |
\b |
Word boundary: the edge between a word character and anything else |
(?=...) (?!...) |
Lookahead: followed by, or not followed by |
(?<=...) (?<!...) |
Lookbehind: preceded by, or not preceded by |
Repeats are greedy and take as much as they can. Add ? to make one lazy: on <b>bold</b>, the pattern <.+> matches the whole thing while <.+?> matches <b> and </b> separately. To match a special character literally, put a backslash before it, as in \. or \(.
How JavaScript regex differs from PCRE and Python
The basics above work almost everywhere. The differences show up in the advanced features:
- No possessive quantifiers like
a++and no atomic groups. - No
\Aor\Zanchors. Use^and$without the m flag instead. - Named groups are written
(?<name>...), where Python traditionally uses(?P<name>...). - Unicode classes such as
\p{L}(any letter in any script) need the u flag. - No
(?i)at the start of a pattern to switch on a flag. Tick the flag instead.