实现说明
演示用的数据放在这几个模块级绑定中:log_line、token_re、body_start、body_end。
使用要点
- 不用提前执行安装:样例完全采用官方标准库实现。
- 直接运行文件,输出会带上标签,比如
hits :、redacted:、bounded match:——输出的每一行都能指回产生它的那次调用。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 状态都挂在模块顶层:log_line、token_re、body_start。
代码示例
import re
log_line = "actor=ada token=tok_91ab22 role=ops token=tok_77cd10 status=ok"
token_re = re.compile(r"token=tok_[0-9a-f]+")
# subn returns (new_string, replacement_count) in a single pass
redacted, hits = token_re.subn("token=[REDACTED]", log_line)
print("hits :", hits)
print("redacted:", redacted)
# Passing pos/endpos scans a sub-window without slicing copies, keeping original offsets
body_start = log_line.index("role=")
body_end = log_line.index(" status=")
match = token_re.search(log_line, body_start, body_end)
if match:
print("bounded match:", match.group(0), "at span:", match.span())