Regex Flags
Flags (or modifiers) change how the whole pattern behaves. Six matter most. Here is what each does, with an example and the cross-language differences.
The flags
| Flag | Name | Effect |
|---|---|---|
g | Global | Find all matches, not just the first (JavaScript) |
i | Ignore case | /cat/i matches CAT |
m | Multiline | ^ and $ match at every line break |
s | Dotall / single-line | . also matches newline characters |
u | Unicode | Enables \p{...} and correct handling of astral chars |
y | Sticky | Match only at lastIndex, no scanning ahead (JS) |
How to set them
| Language | Syntax |
|---|---|
| JavaScript | /pattern/gim or new RegExp('pattern','gi') |
| Python | re.compile(r'pattern', re.I | re.M) |
| Inline (PCRE/Python) | (?im)pattern at the start |
| Scoped inline | (?i:abc) — case-insensitive for that group only |
Multiline vs dotall — the common mix-up
They are not the same flag:
mchanges what^and$mean — they anchor to each line instead of the whole string.schanges what.means — it starts matching newlines too.
Confusingly, some engines call s the "single-line" flag, which is the opposite name to what it does. Judge by behavior, not the label.
Why g matters in JavaScript
Without g, String.replace replaces only the first match and matchAll throws. With g, a regex also keeps a stateful lastIndex — reusing the same object across .test() calls can give surprising results, so create a fresh regex when in doubt.
FAQ
What is the difference between the m and s flags?
m (multiline) makes ^ and $ match at line breaks. s (dotall) makes the dot match newline characters too. They are independent and often used together.
Does Python have a global flag like JavaScript's g?
No. In Python you choose the behavior by the function: re.findall and re.finditer return all matches, while re.search returns the first. There is no per-pattern global flag.
Why does my /g regex behave differently on repeated calls?
A global regex tracks lastIndex between calls to .test() and .exec(), so the next call resumes where the previous one stopped. Reset lastIndex to 0 or build a new RegExp for a clean start.