Sub topic 4
Detecting structured identifiers with regular expressions
This chapter assumes you can write basic Python and read simple regular expressions (character classes, quantifiers, groups). It covers the first detector in a redaction pipeline. Names and places need a different tool, which a later chapter covers.
Why start with regular expressions
Some personal data has a fixed shape. Email addresses, phone numbers, national ID numbers, IP addresses, and card numbers all follow rules. A regular expression (regex) describes a shape, and a regex engine scans text for it quickly, with no model and no network call. The result is predictable. The same input always gives the same output, which makes the detector easy to test and audit.
Every detector in this tutorial returns the same thing: a list of spans. A span is a tuple (start, end, label). start and end are character offsets into the original text, and label names the kind of data. Later steps such as redaction and overlap resolution only need spans, so they work with any detector.
A first detector: email addresses
import re
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
def find_emails(text):
return [(m.start(), m.end(), "EMAIL") for m in EMAIL_RE.finditer(text)]
print(find_emails("Contact [email protected] or [email protected]"))This prints [(8, 23, 'EMAIL'), (27, 42, 'EMAIL')]. The pattern has three parts:
- A local part: letters, digits, and the symbols
. _ % + -. - A literal
@. - A domain, then a dot, then a top-level domain of at least two letters.
finditer returns every match with its position. Use it instead of findall, which returns only the matched strings and loses the offsets.
Several patterns, one list of spans
Real inputs contain more than one kind of identifier. Keep the patterns in a dictionary keyed by label, and run each one over the text.
import re
PATTERNS = {
"EMAIL": re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
"US_SSN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
"IPV4": re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
}
def find_all(text):
spans = []
for label, rx in PATTERNS.items():
spans.extend((m.start(), m.end(), label) for m in rx.finditer(text))
return sorted(spans)
print(find_all("Mail [email protected] from 10.0.0.12, SSN 123-45-6789"))The output is [(5, 20, 'EMAIL'), (26, 35, 'IPV4'), (41, 52, 'US_SSN')]. Adding a new identifier type means adding one dictionary entry.
Common errors
Regex detectors fail in two ways, and you need to watch for both.
- False positives. The pattern matches text that is not personal data. The IPv4 pattern above accepts
999.999.999.999and software versions like1.2.3.4. A broad card pattern matches order numbers. - False negatives. Real data is written in a way the pattern did not expect. The SSN pattern misses
123 45 6789and123456789. The email pattern misses addresses with non-ASCII characters.
Tightening a pattern reduces false positives but tends to add false negatives. For redaction, a missed identifier is usually worse than an extra match, so start with a broad pattern and then filter its matches. The next chapter does this with checksums.
Other points to keep in mind:
- Compile patterns once at module level, as shown. Do not rebuild them per request.
- Avoid nested quantifiers such as
(a+)+. On crafted input they can cause catastrophic backtracking, which makes the scan very slow. User text is untrusted input. - Offsets refer to the exact string you scanned. If you normalize the text first (lowercasing, Unicode normalization), keep the original offsets or scan the original.
- Two patterns can match overlapping text, for example a phone number inside a longer digit run. Detecting is separate from resolving overlaps, which a later chapter covers.
Exercise
The SSN pattern \b\d{3}-\d{2}-\d{4}\b is run on "Ref 123-45-67890". Does it match, and why does the answer matter for choosing patterns?
Show answer
It does not match. After 6789 the next character is 0, a word character, so there is no word boundary at the end. This shows that \b prevents matches inside longer digit strings, which reduces false positives. Because the pattern is strict, it also misses variants such as 123456789, so you must test for both false positives and false negatives.