本文详解如何使用 `re.multiline` 与合理锚点设计,配合非贪婪匹配和负向先行断言,可靠提取 `start_of_compile` 与 `end_of_compile` 之间所有非注释行内容,避免 `none.group()` 错误。
在处理自定义标记的配置文件或生成脚本(如 .qel 文件)时,常需提取两个固定分隔符之间的多行文本。但直接使用 .* 默认不匹配换行符,而错误地依赖 re.MULTILINE(它仅影响 ^/$ 的行为,不启用 . 匹配换行),会导致 re.match() 返回 None,进而触发 AttributeError: ‘NoneType’ object has no attribute ‘group’。
根本原因有三:
- re.MULTILINE ≠ re.DOTALL:re.MULTILINE 让 ^ 和 $ 匹配每行首尾,但 . 依然不匹配 \n;真正让 . 匹配包括换行符在内的任意字符的是 re.DOTALL(即 re.S)。
- 锚点 ^ 在 re.MULTILINE 下才生效:你的原始正则以 ^#+\n 开头,若未启用 re.MULTILINE,^ 只匹配整个字符串开头,而示例中 #####start_of_compile… 前无换行,导致匹配失败。
- 贪婪匹配易越界:.* 默认贪婪,可能跨过 end_of_compile 继续匹配,尤其当结尾存在多行 # 时;应结合负向先行断言 (?!#+$) 精确控制边界。
✅ 推荐正则方案(兼顾鲁棒性与可读性):
import re
def extract_compile_block(filepath: str) -> str:
with open(filepath, "r") as f:
content = f.read()
# 关键:re.MULTILINE + 精确行锚定 + 负向断言防跨界
pattern = r'^#+\n#+start_of_compile\b.*\n#+\n\s*^(.+(?:\n(?!#+$).*)*)\n\s*^#+\n#+end_of_compile\b'
match = re.search(pattern, content, re.MULTILINE)
if not match:
raise ValueError("Failed to locate start_of_compile / end_of_compile block")
return match.group(1).strip() # 自动去除首尾空白行
# 使用示例
try:
result = extract_compile_block("compile.qel")
print(repr(result)) # 显示含换行符的原始内容
# 输出: 'parse these lines in between them\n...\n....'
except (FileNotFoundError, ValueError) as e:
print(f"Error: {e}")
? 关键细节说明: