The flags are where most confusion lives
Four switches change everything, and picking the wrong one costs more debugging time than the pattern itself.
- g — find every match instead of stopping at the first. Without it, only one result comes back.
- i — ignore case, so
Catandcatboth match. - m — make
^and$mean start and end of each line rather than of the whole text. This is the one people expect by default and rarely get. - s — let
.match newlines too, which it otherwise refuses to do.
Capture groups, and why they are numbered
Parentheses do two jobs at once: they group part of the pattern, and they capture what matched inside them. Groups are numbered from left to right by their opening parenthesis, starting at 1 — group 0 is always the whole match.
This tool lists each group separately for every match, which is the fastest way to find out that your group 2 is not what you assumed. When you only need grouping without capture, use (?:…) and the group stops consuming a number.
Frequently asked questions
Which regex flavour is used?
JavaScript's, since evaluation happens in your browser. It is very close to PCRE but lookbehind support depends on your browser version.
Why does my pattern only find one match?
The g flag is off. Without it, the search stops at the first result.
Why does ^ not match the start of my lines?
Because it means start of the whole text unless the m flag is enabled.
Is my text sent to a server?
No, the regex runs locally in your browser.