示例工程 16-stdlib-tour

16-stdlib-tour/02-re-named-groups/re_named_groups.py

python · 1.0 KB

"""演示 re 的命名分组、finditer 与 sub 回调。"""
 
from __future__ import annotations
 
import re
 
LOG = re.compile(r"(?P<level>INFO|WARN|ERROR) (?P<service>[\w-]+): (?P<message>.+)")
 
 
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')}: <redacted>"
 
    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()