A credit-card regex will pass every audit and still leak the personal data that actually matters. Names, addresses, free-text notes — that is where the disclosure risk lives, and a regex never sees it.
Most PII detection in a data pipeline is a handful of regular expressions bolted on late: one for card numbers, one for email addresses, maybe one for a national identifier. It gets written because someone asked “do we scan for personal data before it lands in the warehouse?” and a regex is the fastest thing that answers yes. It catches the formatted, structured identifiers — and it is blind to almost everything else. The engineering problem is not detecting a sixteen-digit number. It is detecting a person’s name in a support ticket, an address in a chat transcript, or a health detail in a free-text note. That is where the real exposure sits, and it needs more than pattern matching.
Why regex is the wrong tool for most personal data
Regex is excellent at one thing: identifiers with a deterministic shape. A card number, an IBAN, a UK National Insurance number — each has a fixed structure you can express as a pattern. For those, regex is the right tool and you should keep using it.
Free · 4 minutes
Would you survive contact with a determined attacker — or an auditor?
Fourteen questions on access, patching, detection, and recovery — the basics that prevent most real incidents, and the ones most often assumed rather than verified. Banded finding on screen, full sheet by email.
The problem is that most personal data has no shape. A name is just a sequence of capitalised words that could equally be a place, a product or a company. An address has loose, variable structure that shifts by country. A free-text field — “spoke to Maria about her son’s operation on Tuesday” — carries name and special-category health data with no pattern to match at all. Regex has no concept of context and no concept of confidence. It either matches or it does not, and it cannot tell you how sure it is. That binary is the wrong model for language, and language is where the under-detected personal data hides.
What Presidio does differently
Microsoft Presidio is an open-source framework for detecting and de-identifying PII. What makes it worth adopting is that it does not rely on a single technique. It combines three signals and reconciles them into a confidence score per finding.
Named-entity recognition. Presidio runs an NLP model — spaCy by default, or a transformers model if you want higher accuracy at higher cost — to find entities such as PERSON, LOCATION and DATE_TIME. This is what catches the name a regex cannot, because the model has learned what a name looks like in context rather than by shape.
Pattern recognisers with validators. For structured identifiers Presidio still uses regex, but it pairs the pattern with a checksum where one exists. The built-in credit-card recogniser runs a Luhn check, so a random sixteen-digit order reference does not score the same as a genuine card number. The pattern narrows the field; the validator confirms it.
Context enhancement. Presidio adjusts confidence based on nearby words. Its default LemmaContextAwareEnhancer lifts a finding’s score when a supporting term appears close by — the word “card” near a candidate number, “policy” near an internal reference. The default boost is a similarity factor of 0.35 with a minimum resulting score of 0.4. A weak pattern match that would otherwise be discarded is promoted when the context supports it, and left alone when it does not.
The output is not a yes or no. It is an entity type, a position and a score. That score is the whole point.
Precision versus recall is your decision, not the tool’s
Because every finding carries a confidence score, you set a threshold — and that threshold is a governance choice, not a default to accept unread. Set it low and you catch more real PII while redacting more false positives, which quietly breaks analytics: mask every number that looks vaguely like an identifier and your fraud model loses the signal it was built on. Set it high and you leak the borderline cases the model was unsure about. Under-detection is a data-protection failure; over-detection is a data-quality failure. Both are engineering decisions, and both should be made deliberately rather than inherited from a library’s defaults.
The practical consequence is that the threshold belongs per data domain, not once for the whole estate. A free-text medical note and a machine-generated event log carry very different risk and very different base rates, so they warrant different dials. Owning that decision is the difference between a detection layer you can defend to a supervisor and one you cannot explain.
Build it as a service, not scattered library calls
The failure mode I see is Presidio imported into six different jobs, each configured slightly differently, none tested against a shared corpus. Detection logic drifts, thresholds diverge, and nobody can say what the pipeline as a whole actually catches. Treat detection as one reusable service that pipelines call before data lands. It gives you a single place to version recognisers, add domain-specific patterns, and run a regression suite of known cases so a model or configuration change cannot silently degrade recall.
The service is where custom recognisers live — an internal policy number, a customer reference, a scheme identifier the built-in set does not know. Each is a pattern plus its context words, registered once and reused everywhere.
"""pii_service.py — reusable detection/redaction, called before data lands."""
from presidio_analyzer import AnalyzerEngine, Pattern, PatternRecognizer
from presidio_analyzer.nlp_engine import NlpEngineProvider
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
# Load the NLP engine once at start-up; the models are expensive to initialise.
nlp_engine = NlpEngineProvider(nlp_configuration={
"nlp_engine_name": "spacy",
"models": [{"lang_code": "en", "model_name": "en_core_web_lg"}],
}).create_engine()
analyzer = AnalyzerEngine(nlp_engine=nlp_engine, supported_languages=["en"])
# A domain identifier's regex alone is weak; the context words lift its
# confidence when they appear nearby, which cuts the false-positive rate.
policy_ref = PatternRecognizer(
supported_entity="POLICY_NUMBER",
patterns=[Pattern(name="policy_ref", regex=r"\bPOL-\d{8}\b", score=0.4)],
context=["policy", "cover", "renewal", "claim"],
)
analyzer.registry.add_recognizer(policy_ref)
anonymizer = AnonymizerEngine()
# The threshold is a deliberate precision/recall dial, tuned per data domain.
SCORE_THRESHOLD = 0.6
def redact(text):
results = analyzer.analyze(
text=text,
language="en",
entities=["PERSON", "LOCATION", "EMAIL_ADDRESS",
"CREDIT_CARD", "IBAN_CODE", "POLICY_NUMBER"],
score_threshold=SCORE_THRESHOLD,
)
cleaned = anonymizer.anonymize(
text=text,
analyzer_results=results,
operators={"DEFAULT": OperatorConfig("replace",
{"new_value": "<REDACTED>"})},
)
# Return the clean text plus an audit trail of what was found and how sure.
return {"text": cleaned.text,
"found": [(r.entity_type, round(r.score, 2)) for r in results]}
if __name__ == "__main__":
sample = ("Spoke to Maria Alvarez about policy POL-40118322; "
"card 4095-2609-9393-4932.")
print(redact(sample))
The stream consumer calls redact for every record before it is written downstream. Keeping the found list gives you an audit trail: what was detected, at what confidence, which is exactly what you want when a threshold change needs justifying.
Where this sits in the wider control set
Detection does not stand alone. You cannot reliably scan for personal data you have never mapped, which is why a detection service works best alongside a live record of where personal data is meant to flow — the same discipline behind treating your Article 30 record as code rather than a spreadsheet. And the pattern of putting a tested, versioned processing stage in front of data as it moves is the same one that makes an incident-reporting pipeline dependable: the value is in the engineering rigour around it, not the library itself.
Regex tells you a string looks like a card number. It tells you nothing about the person named three words later. If your pipeline only checks for shapes, it is not detecting personal data — it is detecting the personal data that was easy to find, and calling the rest clean.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Free interactive tool
Interactive deadline calculator
Check which regulations apply to you and when
Regulation across the EU, UK, US and Asia-Pacific has moved considerably in the past eighteen months, and several headline dates have shifted more than once. Twelve questions, about three minutes.
Results are shown on screen — no email required. A dated summary is available to download, and can be sent on if that's more useful. What we do with your answers.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.
Full Governance by Sixteen Pillars
Govern your business. Prove your compliance.
A board assurance cockpit for EU-regulated financial firms — tamper-evident, hash-chained proof of governance across DORA, GDPR, NIS2, ISO 27001, the EU AI Act and MiCA. In development.
See what's coming