Sub topic 4
Detecting Structured Identifiers with Regular Expressions
This chapter assumes you know basic Python (functions, lists, dictionaries) and the regular expression syntax for character classes, quantifiers, groups, and anchors. It also assumes you have seen the earlier chapters on kinds of personal data and where that data flows in an LLM app. Here you build detectors for identifiers that have a fixed shape: emails, phone numbers, and IP addresses. Every detector returns the same output, a list of (start, end, label) spans. The later chapters on checksums, named-entity recognition (NER), and redaction all consume that shape.
Why regular expressions come first
Structured identifiers follow a format. An email has a local part, an @, and a domain. An IPv4 address has four numbers separated by dots. A pattern can describe a format, so a regular expression is the cheapest detector to write. It is also fast, deterministic, and easy to explain to an auditor.
Regular expressions are the wrong tool for identifiers with no format. A person's name or home city has no pattern, and NER handles those. A regular expression also cannot tell a valid card number from a random 16-digit string, which is a job for checksums.
Aim for these properties in each detector:
- High recall on well-formed values. If a value is an email, the pattern should find it.
- Few false positives. Order numbers and version strings should not match.
- Spans, not just booleans. You need character offsets so a later step can replace exactly the right text.
- Bounded cost. Matching time should not blow up on hostile input.
The span contract
A span is a tuple (start, end, label). start is the index of the first character, end is the index after the last character (Python slice convention), and label names the kind of data. With this convention, text[start:end] returns the matched value.
The email detector from the plan shows the contract:
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')]. Use finditer, not findall. findall returns strings (or group tuples) and drops the offsets.
Reading the email pattern
| Part | Meaning |
|---|---|
| `\b` | Word boundary, so the match does not start in the middle of a longer word |
| `[A-Za-z0-9._%+-]+` | Local part: letters, digits, and the common punctuation |
| `@` | Literal at sign |
| `[A-Za-z0-9.-]+` | Domain labels, possibly with dots |
| `\.[A-Za-z]{2,}` | A final dot and a top-level domain of two or more letters |
| `\b` | Word boundary at the end |
The final \.[A-Za-z]{2,} is what rejects ana@example (no top-level domain). The pattern backtracks so that mail.example.co.uk is matched as one domain.
Adding more detectors
Keep patterns in a dictionary keyed by label. One loop then runs all of them, and adding a detector means adding one entry.
import re
PATTERNS = {
"EMAIL": re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
"PHONE": re.compile(
r"(?<!\w)(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)|\d{3})[ .-]?\d{3}[ .-]?\d{4}(?!\w)"
),
"IPV4": re.compile(
r"(?<![\d.])(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}"
r"(?:25[0-5]|2[0-4]\d|1?\d?\d)(?!\d)(?!\.\d)"
),
}
def detect(text):
spans = []
for label, pattern in PATTERNS.items():
for m in pattern.finditer(text):
spans.append((m.start(), m.end(), label))
return sorted(spans)
text = "Mail [email protected], call +1 415-555-0132, host 10.0.0.7."
for start, end, label in detect(text):
print(label, repr(text[start:end]))The output is:
EMAIL '[email protected]'
PHONE '+1 415-555-0132'
IPV4 '10.0.0.7'Why the patterns use lookarounds
\b only works between a word character and a non-word character. A phone number can start with + or (, which are not word characters, so \b before them behaves unpredictably. The phone and IPv4 patterns use lookarounds instead:
(?<!\w)means "not preceded by a letter, digit, or underscore".(?!\w)means "not followed by a letter, digit, or underscore".(?<![\d.])and(?!\d)(?!\.\d)keep an IP address from matching inside1.2.3.4.5or999.1.1.1, but still allow a sentence-ending period as in10.0.0.7..
Lookarounds consume no characters, so they do not become part of the span. The span covers only the identifier.
The IPv4 octet
A loose pattern like \d{1,3} would accept 999. The octet pattern 25[0-5]|2[0-4]\d|1?\d?\d accepts only 0 to 255. The order of the alternatives matters. Python tries them left to right, so the specific 25[0-5] comes before the general 1?\d?\d. If you reversed them, 250 could match as 25 followed by a failed dot.
How a detector processes text
The scanners do not know about each other. That is simple, but it means two patterns can claim the same characters. A later chapter covers overlap resolution. For now, remember that sorted(spans) orders by start, then end, and does not remove overlaps.
Testing patterns before trusting them
A regular expression that looks right often is not. Write a small table of positive and negative cases and run it each time you change a pattern. Use fullmatch so the whole string must match.
import re
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
cases = [
("[email protected]", True),
("[email protected]", True),
("ana@example", False),
("ana@@example.com", False),
("[email protected]", False),
("ana.o'[email protected]", True), # what we want
]
for value, expected in cases:
actual = EMAIL_RE.fullmatch(value) is not None
status = "ok " if actual == expected else "FAIL"
print(status, value, "expected", expected, "got", actual)The last case prints FAIL. The apostrophe is legal in the local part of an email, but the character class does not include it. This is a false negative: a real email that the detector misses. For a privacy filter, a miss is worse than a false alarm, because the value reaches the model. Adding ' to the local-part class fixes this case.
Common errors
1. Using `findall` and losing offsets
re.findall returns matched strings or, when the pattern has groups, only the group contents. Neither tells you where the value sits. Redaction needs offsets, so use finditer.
2. Unescaped dots
In [A-Za-z0-9.-], the dot inside a character class is literal. Outside a class, . matches any character. A pattern like example.com also matches exampleXcom. Write \. when you mean a literal dot.
3. Patterns that are too broad
\d{10} matches any ten digits, including order numbers and timestamps. Use boundaries and, where the format allows, separators. Even then, a 10-digit phone pattern will sometimes match a non-phone value. Decide whether you prefer a few extra redactions or a few misses, and tune toward that choice.
4. Formats that vary by country
The phone pattern above fits North American numbers with an optional country code. A UK number such as +44 20 7946 0958 will not match. Do not stretch one pattern to cover every country. Use separate labelled patterns, or use a library such as phonenumbers that knows national formats.
5. Catastrophic backtracking
Nested quantifiers such as (a+)+$ can take exponential time on input like aaaaaaaaaaaaaaaaaaaaaaaa!. Prompts come from users, so a hostile user can freeze a request handler. The patterns in this chapter use flat character classes with single quantifiers, which avoids the problem. When you write a new pattern, avoid a quantified group that contains another quantifier, and test it against long strings that almost match.
Do not run untrusted input through a regular expression you have not tested against long, nearly matching strings. Slow patterns on user-controlled text are a denial-of-service risk. Consider capping input length before detection.6. Flags and Unicode
In Python 3, \w and \d match Unicode letters and digits by default. \d therefore matches Arabic-Indic digits such as ٣, which int() accepts but a strict format may not want. If you want ASCII-only behaviour, write [0-9] or pass re.ASCII. In the other direction, the email pattern uses [A-Za-z], so it misses internationalized addresses with non-Latin letters. Decide which behaviour your app needs and record it.
Decision criteria: when a regular expression is enough
| Situation | Regex alone | Add something |
|---|---|---|
| Emails, URLs, IP addresses | Usually enough | Context rules for edge cases |
| Phone numbers | Works per country | A library for national formats |
| Card numbers, national IDs with check digits | Finds candidates | Checksum validation to cut false positives |
| Names, street addresses, organizations | Poor fit | NER |
A practical rule is to start with a deliberately broad regular expression for recall, then add validation (the next chapter) for precision. A broad pattern plus a validator is easier to reason about than one very narrow pattern that tries to do both.
Summary of the working model
- A detector is a function from text to a list of
(start, end, label)spans. - Use
finditerfor offsets, and keep one compiled pattern per label. - Use lookarounds instead of
\bwhen an identifier can start or end with a symbol. - Test each pattern against positive and negative cases, and watch for false negatives.
- Keep patterns linear and cap input length.
Exercise
A teammate wrote the pattern \d{3}-\d{2}-\d{4} to find US Social Security numbers and uses re.findall to collect them. Name two problems with this approach for a redaction pipeline, and give a fix for each.
Show answer
First, findall returns only the matched strings, not their positions, so the pipeline cannot replace the text at the right place. Use finditer and build (m.start(), m.end(), "SSN") spans. Second, the pattern has no boundaries, so it also matches inside longer digit strings such as 1234-56-78901, producing a false positive in the middle of another value. Add lookarounds: (?<!\d)\d{3}-\d{2}-\d{4}(?!\d). A further improvement is to reject known-invalid ranges (such as area number 000 or 666) in a validation step after the match.
Exercise
Extend the PATTERNS dictionary with a "URL" label that matches http:// or https:// followed by non-whitespace characters, without including a trailing period or comma. Which function in the chapter do you call to get spans, and what does sorted do to the result?
Show answer
Add "URL": re.compile(r"https?://[^\s]+[^\s.,;:!?)]"). The final class excludes common trailing punctuation, so see https://example.com/a. matches without the period. Call detect(text), which loops over every pattern and collects (start, end, label) tuples. sorted orders them by start and then end, so the spans are in text order. It does not remove overlaps, so two patterns that match the same characters would both stay in the list.