Sub topic 5
Reducing false positives with checksums
This chapter assumes you can write basic Python and read simple regular expressions. It also assumes you know that a detector returns (start, end, label) spans, as in the email example from the previous chapter.
Why a pattern alone is not enough
A regular expression checks the shape of text, not its meaning. A card-number pattern matches any run of 13 to 19 digits, so it also matches order numbers, tracking codes, and phone numbers. If you redact all of those, the model loses context it needs. If you skip the pattern, real card numbers leak.
Many structured identifiers carry a built-in check digit. A checksum is a small calculation over the digits that a real identifier passes and most random digit strings fail. The pattern finds candidates, and the checksum discards the ones that cannot be real.
The Luhn algorithm
Payment card numbers use the Luhn algorithm. It works from the rightmost digit:
- Starting at the right, leave the last digit as it is.
- Double every second digit moving left.
- If a doubled digit is above 9, subtract 9.
- Add all digits. The number is valid if the total is divisible by 10.
Putting it together
The code below uses a broad pattern for candidates. The luhn_valid function strips spaces and dashes, checks the length, and applies the algorithm.
import re
CARD_RE = re.compile(r"\b(?:\d[ -]?){13,19}\b")
def luhn_valid(number: str) -> bool:
digits = [int(c) for c in number if c.isdigit()]
if not 13 <= len(digits) <= 19:
return False
total = 0
for i, d in enumerate(reversed(digits)):
if i % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def find_cards(text):
return [
(m.start(), m.end(), "CREDIT_CARD")
for m in CARD_RE.finditer(text)
if luhn_valid(m.group())
]
print(find_cards("Card 4111 1111 1111 1111, order 1234567890123"))The output is one span for 4111 1111 1111 1111, which is a well-known test card number. The order number 1234567890123 has 13 digits and matches the pattern, but its Luhn total is not divisible by 10, so it is dropped.
Note that enumerate(reversed(digits)) gives index 0 to the last digit. That is why the code doubles when i % 2 == 1.
Common errors
- Doubling the wrong digits. Counting from the left breaks the check for numbers whose length is odd. Always count from the right.
- Forgetting to strip separators. The regex allows spaces and dashes, so the validator must ignore them. Here
luhn_validkeeps only digit characters. - Dropping the length check. Short digit strings pass Luhn often enough to cause false positives.
- Treating a pass as proof. About one in ten random digit strings passes Luhn by chance. A passing number is likely a card, not certainly one.
- Trailing separators in the span. The pattern
(?:\d[ -]?)can include a trailing space or dash in the match. The span may then be a character too long. You can trim it withm.group().rstrip(" -")and adjustend.
Other identifiers with check digits
Luhn is not the only scheme. Other identifiers carry their own checks:
| Identifier | Check method |
|---|---|
| Payment card number | Luhn |
| IBAN (bank account) | Mod 97 over the rearranged string |
| ISBN-13 (book) | Weighted sum of digits, mod 10 |
| National IDs | Varies by country, often a weighted mod check |
The structure is the same each time. A broad regex finds candidates and a validator function confirms them. Keeping the validator separate from the regex makes it easy to test on its own.
Exercise
The text "Ref 4111111111111112" contains 16 digits that match the card regex. The last digit of the valid test card 4111111111111111 was changed from 1 to 2. Will find_cards report it, and why?
Show answer
No. Changing one digit changes the Luhn total so it is no longer divisible by 10. The regex still matches, but luhn_valid returns False, so the candidate is discarded.
Exercise
Why does find_cards use a broad regex plus a validator instead of one stricter regex?
Show answer
Luhn is arithmetic, which a regular expression cannot express. The regex only needs to find possible candidates cheaply, and the validator removes most false positives.