Skip to main content
A regular expression (regex) is a pattern that describes text to match. Instead of searching for one exact string, a regex describes a shape: “a word boundary, then some letters, then a boundary”, “any digit repeated three times”, “one of these three words”. Anywhere you’re asked for a regex pattern, it’s evaluated with JavaScript’s regex engine, the same one described here.

How it works

A pattern is built from a small set of building blocks, combined together.

Literal characters

Most characters just match themselves. The pattern cat matches the text cat wherever it appears.

Character classes

A character class matches one character out of a set.

Quantifiers

A quantifier says how many times the thing before it can repeat. Quantifiers are greedy by default: they match as much as possible before backing off. Adding ? after a quantifier (*?, +?) makes it lazy instead, matching as little as possible.

Anchors and boundaries

\bcat\b matches cat as its own word, not the cat inside catalog.

Groups and alternation

Parentheses () group part of a pattern together, so a quantifier can apply to the whole group and so the matched text can be extracted separately. The pipe | inside or around a group means “or”: cat|dog matches either cat or dog.

Escaping

Characters like . * + ? ( ) [ ] { } ^ $ | are special to regex. To match one of them literally, put a backslash in front of it: \. matches a literal period, \( matches a literal opening parenthesis.

Flags

Flags go after the pattern and change how the whole match runs.

Playground

Edit the pattern, flags and test message below. Matches are highlighted live.

Examples

Some patterns can run very slowly on certain input, particularly nested repetition like (a+)+b. If a pattern needs to run against arbitrary user-supplied text, test it against a long, unusual input in the playground above before relying on it.

Related topics

Jail