"""演示 re 的命名分组、finditer 与 sub 回调。""" from __future__ import annotations import re LOG = re.compile(r"(?PINFO|WARN|ERROR) (?P[\w-]+): (?P.+)") def parse(line: str) -> dict[str, str] | None: match = LOG.match(line) if match is None: return None return match.groupdict() def redact(line: str) -> str: def replace(match: re.Match[str]) -> str: return f"{match.group('level')} {match.group('service')}: " return LOG.sub(replace, line) def main() -> None: lines = [ "INFO api: started", "ERROR db: connection lost", "not a log line", ] for line in lines: print(f"parse {line!r}: {parse(line)}") joined = "\n".join(lines[:2]) print(f"levels: {[match.group('level') for match in LOG.finditer(joined)]}") print(f"redacted: {redact(lines[1])}") print(f"start_only: {re.match('api', lines[0]) is not None}") print(f"pattern: {LOG.pattern}") if __name__ == "__main__": main()