Regex · Find all matches instead of only the first
Regex flags
Flags change how a pattern is interpreted: global, case-insensitive, multiline, dot-all, Unicode, sticky and indices.
Key facts
| g | Find all matches instead of only the first |
|---|---|
| i | Case-insensitive matching |
| m | <code>^</code> and <code>$</code> match line boundaries |
| s | Dot matches newline as well |
| u | Unicode mode; stricter escapes and code-point matching |
| y | Sticky: match only at lastIndex in JavaScript |
| d | Match indices in JavaScript |
| x | Free-spacing in PCRE and Python, not JavaScript |
Flags are part of the pattern
The same source text can match or fail depending on flags. Without s, the dot excludes newline characters; without m, anchors refer to the whole input. Case-insensitive mode uses locale or Unicode case folding depending on the engine, which changes whether “ß” matches “SS”.
In JavaScript, the g flag makes a RegExp object stateful: lastIndex advances after each match, so reusing the same object on a new string can start in the middle. Create a fresh object or reset lastIndex to zero.
Unicode and sticky modes
The u flag switches JavaScript to code-point semantics and rejects useless escapes, which is why some old patterns throw when it is enabled. It also makes quantifiers apply to whole code points instead of UTF-16 code units, fixing emoji and astral-character matches.
Sticky mode (y) anchors the match at lastIndex without searching forward — useful for tokenizers. Free-spacing (x) ignores whitespace in the pattern and allows comments, but only in engines that implement it; a spaced pattern pasted into JavaScript will not compile.
Frequently asked questions
What does the g flag do?
It makes the engine find all matches rather than stopping at the first, and in JavaScript it advances lastIndex between calls.
What is the difference between m and s flags?
m makes ^ and $ match line boundaries; s makes the dot match newline. They solve different problems and can be combined.
Can I use the x flag in JavaScript?
No. Free-spacing is a PCRE and Python feature; JavaScript patterns must not rely on it.