Multiline And DotAll Regex Flags
The m flag anchors ^ and $ at every line break while s lets dot cross newlines, together enabling per-line scanning of multi-line records.
Code
// Both flags change what anchors and dots match: m per line, s across lines
const log = 'INFO boot ok\nERROR disk full\nINFO ready';
console.log('without m, ^ matches only index 0:', /^ERROR/.test(log));
console.log('with m, ^ scans every line:', /^ERROR/m.test(log));
// per-line extraction: m makes ^ match at the start of each line
const levels = [...log.matchAll(/^(ERROR|INFO)/gm)].map((match) => match[1]);
console.log('levels:', levels);
// dotAll: a single dot now spans line breaks inside one record
const record = 'begin AAA\nBBB end';
console.log('dot stops at newline:', /begin.*end/.test(record));
console.log('dotAll spans lines:', /begin.*end/s.test(record));
// combined: grab a whole two-line error block from the log
const block = log.match(/^ERROR.*$\n.*$/m);
console.log('error block:', block && block[0].replace('\n', ' | '));Reading the snippet
The file’s state is a handful of top-level bindings: log, levels, record, block.
Caveats
- Everything it calls is documented as part of the language core.
Using it
The run emits 6 labeled sections — without m, ^ matches only index 0:, with m, ^ scans every line:, levels:, dot stops at newline:, dotAll spans lines:, error block: — one per step.
Key statements
const levels = [...log.matchAll(/^(ERROR|INFO)/gm)].map((match) => match[1]);
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `log`, `levels`, `record`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.