re.sub Callback Redacts Matched Secrets

Pass a function to re.sub so every match decides its own replacement: redact secrets with shape preserved, normalize codes, and bump versions in a single pass.

PythonSecurity Boundaries

Code

pythonsnippet
19 lines
import re

# 传函数而不是固定字符串:每个匹配自带处理逻辑
LOG_LINE = "user=jules token=eyJhbGciOi9f8e sku=QX-2231 [email protected] ok"

SECRET = re.compile(r"(token=)\S+|(email=)\S+")
redacted = SECRET.sub(lambda m: (m.group(1) or m.group(2)) + "[REDACTED]", LOG_LINE)
print("redacted:", redacted)

# 归一化:把自由文本里的 sku 编码统一成大写形式
def upper_sku(m):
    return "SKU-" + m.group(1).upper()

catalog = "items: sku-ab12, sku-cd34, sku-ef56"
print("normalized:", re.sub(r"sku-([a-z0-9]+)", upper_sku, catalog))

# 分组捕获进回调:一次遍历同时读值并改写,不用先找再换
bumped = re.sub(r"v([0-9]+)\.([0-9]+)", lambda m: f"v{m.group(1)}.{int(m.group(2)) + 1}", "v2.3 v2.10")
print("bumped:", bumped)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

redacted: user=jules token=[REDACTED] sku=QX-2231 email=[REDACTED] ok
normalized: items: SKU-AB12, SKU-CD34, SKU-EF56
bumped: v2.4 v2.11

How it works

re.sub Callback Redacts Matched Secrets keeps everything in the function upper_sku.

Using it

Entry signature: def upper_sku(m)

Running the file prints labeled results such as redacted:, normalized:, bumped: — each operation’s effect is visible in the output.

upper_sku is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def upper_sku(m):
    return "SKU-" + m.group(1).upper()

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `re`. The file defines `upper_sku` at load time.