← 中文资源

简体中文版本

m 与 s 正则标志联动

m 标志让 ^ 与 $ 对齐每一行边界,s 标志让点号跨越换行:两者配合即可逐行扫描多行日志,或用一条模式抓出完整的两行错误块。

阅读英文原文

实现说明

log、levels、record、block 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——without m, ^ matches only index 0:、with m, ^ scans every line:、levels:。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 状态都挂在模块顶层:log、levels、record。

核心语句

const levels = [...log.matchAll(/^(ERROR|INFO)/gm)].map((match) => match[1]);

代码示例

// 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', ' | '));