← 中文资源

简体中文版本

用 re.subn 统计替换次数并按边界下标匹配

调用 re.subn 在单次正则扫描中同步返回脱敏文本与命中计数,再借助编译正则的 pos 与 endpos 参数直接限定搜索窗口并保留原始字符偏移。

阅读英文原文

运行结果

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

hits    : 2
redacted: actor=ada token=[REDACTED] role=ops token=[REDACTED] status=ok
bounded match: token=tok_77cd10 at span: (36, 52)

实现说明

演示用的数据放在这几个模块级绑定中: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())