Lesson 3
Flags and Matching Modes
Global, case-insensitive, multiline, dotAll, and Unicode matching.
Flags change how the engine scans input—not what characters mean. In JavaScript, flags appear after the closing / or as the second argument to new RegExp(pattern, flags).
Common flags (JavaScript)
| Flag | Name | Effect |
|---|---|---|
g | global | Find all matches, not just the first |
i | ignore case | A matches a |
m | multiline | ^ and $ match line boundaries, not only string ends |
s | dotAll | . matches newline characters |
u | Unicode | Unicode-aware \u{...} and some property escapes |
y | sticky | Match only at lastIndex (advanced iteration) |
Other languages expose similar switches (re.IGNORECASE, (?i), etc.) with slightly different names.
Global matching matters
Without g, String.prototype.match and many exec loops stop after the first hit. Log parsers and highlight tools almost always need global mode—or explicit iteration.
Watch stateful regex objects: a global RegExp updates lastIndex. Reusing one instance across unrelated strings can skip matches unless you reset lastIndex.
Multiline log files
Log files contain many lines. With m, ^ERROR matches lines that start with ERROR, which is usually what you want. Without m, ^ often means only the very start of the entire blob.
Combine with g to find every error line in a paste.
DotAll and pasted content
User input and JSON strings may include \n. By default . does not cross lines; s (dotAll) lets . match them—useful for “anything until closing tag” patterns when you accept the risk of over-matching.
Unicode and international text
User names, cities, and slugs may include non-ASCII letters. The u flag enables correct handling of surrogate pairs and \p{...} property classes in modern JavaScript.
Without Unicode awareness, \w might miss valid characters in internationalized apps.
Key takeaway
When a pattern “works on one line but not the file,” check flags first—especially g, m, and s. Then re-check anchors and greediness.