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.
Code
import re
# 传函数而不是固定字符串:每个匹配自带处理逻辑
LOG_LINE = "user=jules token=eyJhbGciOi9f8e sku=QX-2231 email=jules@example.com 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.11How 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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.PII Text CensorDetect and redact emails, phone numbers, credit card numbers, and US Social Security numbers in text, reporting how many of each were masked.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.