re.subn Counts Redactions and Slices Pattern Bounds
Audit text replacements in one pass with re.subn returning (text, count), and scan bounded slices using compiled pattern pos and endpos offsets.
Code
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())Output
Captured from a sandboxed run of this snippet in the build pipeline.
hits : 2
redacted: actor=ada token=[REDACTED] role=ops token=[REDACTED] status=ok
bounded match: token=tok_77cd10 at span: (36, 52)How the snippet works
Demo state sits in top-level bindings: log_line, token_re, body_start, body_end.
What to watch for
- External package managers stay unused since built-in platform APIs back every call.
Using it
The file’s steps show up in the output as hits :, redacted:, bounded match:.
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
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `log_line`, `token_re`, `body_start`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.