← 中文资源

简体中文版本

re 锚点随 MULTILINE 与 DOTALL 变化

默认 ^ 和 $ 只认整串首尾,加 MULTILINE 后逐行生效,DOTALL 让点号跨行匹配;日志逐行提取与跨行字段解析各取所需。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

no flag  : []
MULTILINE: ['ERROR disk full on /var', 'ERROR backup aborted']
DOTALL   : id=7status=okchecksum=abc

实现说明

各个操作都建立在顶层绑定之上:log、record。

使用要点

  • 每一步打印都带着自己的标签:MULTILINE:。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 跨调用保留的状态放在这些顶层绑定里:log、record。

代码示例

import re

log = """INFO boot complete
ERROR disk full on /var
INFO retry scheduled
ERROR backup aborted"""

# Without flags, ^ and $ mean whole-string ends only: no match.
print("no flag  :", re.findall(r"^ERROR.*$", log))

# MULTILINE makes ^ and $ match at every line break.
print("MULTILINE:", re.findall(r"^ERROR.*$", log, flags=re.MULTILINE))

# DOTALL lets . cross newlines, so one pattern can span several lines.
record = "id=7\nstatus=ok\nchecksum=abc"
print("DOTALL   :", re.search(r"id=\d+.*checksum=\w+", record, flags=re.DOTALL).group(0))