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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 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

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`.