Sub topic 5
Reducing false positives with checksums
This chapter assumes you can write basic Python and read a regular expression, and that you have read the previous chapter on regex detection. You should be comfortable with the idea of a detector that returns (start, end, label) spans.
The problem: patterns match too much
A regular expression describes the shape of a string. It cannot tell whether the string means anything. A pattern for card numbers must accept 13 to 19 digits, optionally separated by spaces or hyphens. That pattern also matches order numbers, tracking codes, phone numbers run together, timestamps in milliseconds, and database IDs.
A false positive here is a span your detector flags that is not personal data. False positives cost you in three ways:
- Redacted order numbers or IDs make the model's answer worse. The model can no longer see the value the user asked about.
- Reviewers who see many wrong alerts stop trusting the detector.
- Logs and analytics lose useful fields.
Many structured identifiers are built with a check digit. This is a digit, or a pair of digits, computed from the other digits by a fixed formula. The formula catches typing mistakes, and you can reuse it to filter your regex matches. A random digit string passes the check only by chance, so the check removes most of the noise at almost no cost.
The Luhn algorithm
Payment card numbers use the Luhn checksum. It works like this:
- Take the digits from right to left.
- Double every second digit, starting with the second from the right.
- If doubling gives a number above 9, subtract 9. This equals adding the two digits of the result.
- Add all the digits.
- The number is valid if the sum is divisible by 10.
For 4111 1111 1111 1111, the digits at odd positions from the right are all 1, and each becomes 2 when doubled. That gives eight 2s and eight 1s, so the sum is 24. That is not divisible by 10, which would suggest the number is invalid. Check the arithmetic again: the number is 4111111111111111. Its rightmost digit is 1 (position 0, kept). Position 1 is 1 (doubled to 2). The leading 4 is at position 15, which is odd, so it is doubled to 8. The sum is 7 kept ones, 7 doubled ones (14), the doubled 4 (8) and the kept 1 at position 14... Rather than count by hand, run the code. This is also the better habit: test your validator against known-good and known-bad numbers instead of trusting mental arithmetic.
import re
CARD_RE = re.compile(r"\b\d(?:[ -]?\d){12,18}\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:
[(5, 24, 'CREDIT_CARD')]Both strings match the regex, but only the test card number passes the checksum. The order number 1234567890123 has 13 digits and fails Luhn, so it is not reported.
A change to the regex
A common card pattern is \b(?:\d[ -]?){13,19}\b. Each repetition takes a digit and an optional separator, so the final repetition can swallow a trailing space. In the text Card 4111 1111 1111 1111 expires soon, the match would then include the space after the last digit. Your redaction would eat that space and glue two words together.
The version above, \b\d(?:[ -]?\d){12,18}\b, puts the separator before each digit after the first. A match always starts and ends on a digit, and it still allows 13 to 19 digits in total.
How much does a checksum help?
For a random digit string, the last digit decides whether the sum is divisible by 10. Exactly one of the ten possible last digits makes it valid, so about 1 in 10 random strings passes Luhn. The checksum removes roughly 90% of random false positives. It does not remove all of them.
The checksum also reliably catches:
- Any single wrong digit.
- Most swaps of two adjacent digits. The exception is
09and90.
| Input | Matches regex | Passes Luhn | Reported |
|---|---|---|---|
| `4111 1111 1111 1111` | yes | yes | yes |
| `4111 1111 1111 1112` | yes | no | no |
| `1234567890123` | yes | no | no |
| A random 16-digit order ID | yes | about 1 in 10 | about 1 in 10 |
The last row is the limit of the technique. A valid checksum shows that a string could be a card number. It does not show that it is one, or that it belongs to a real account. Public test numbers such as 4111 1111 1111 1111 pass Luhn, and you should redact them anyway, because you cannot tell test numbers from real ones by checksum.
The two-stage shape
Every checksum detector follows the same structure: a broad regex proposes candidates, and a validator accepts or rejects each one.
Keep the regex broad. If the regex rejects a legitimate format, such as a card number with dots as separators, the validator never sees it and you lose recall. Let the regex over-match and let the validator do the narrowing.
Other identifiers with check digits
Luhn is the most common, but not the only one. Many identifiers carry a check:
- IBAN (international bank account numbers) use a mod-97 check.
- IMEI (mobile device IDs) use Luhn.
- Several national ID and tax numbers use their own weighted sums. Examples include the Spanish DNI letter and the Brazilian CPF digits.
The IBAN check works like this. Move the first four characters to the end. Replace each letter with a number (A is 10, B is 11, up to Z at 35). Read the result as one large integer. The IBAN is valid if that integer modulo 97 equals 1.
import re
IBAN_RE = re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\b")
def iban_valid(value: str) -> bool:
s = value.replace(" ", "").upper()
if not (15 <= len(s) <= 34 and s.isascii() and s.isalnum()):
return False
rearranged = s[4:] + s[:4]
number = "".join(str(int(c, 36)) for c in rearranged)
return int(number) % 97 == 1
def find_ibans(text):
return [
(m.start(), m.end(), "IBAN")
for m in IBAN_RE.finditer(text)
if iban_valid(m.group())
]
print(find_ibans("Pay to GB82 WEST 1234 5698 7654 32 today"))The output is:
[(7, 34, 'IBAN')]int(c, 36) turns 0 to 9 into themselves and A to Z into 10 to 35, which is exactly the IBAN letter mapping. Python integers have no size limit, so the mod-97 step needs no special handling.
Checksums reject too much when text is noisy
A validator is strict, and real text is not. Consider these inputs:
- A user mistypes one digit in their own card number. The number fails Luhn, so your detector skips it. The user's intent was still to share a card number, and the mistyped value still reveals most of the real one.
- OCR output or a copied PDF may swap a
0for anO. The regex might not match at all. - A user splits a number across a line break.
Being strict is correct when the cost of a false positive is high. For privacy, a missed card number is usually worse than a redacted order number. You have three options for the failed candidates:
- Discard them. This is the simplest option, and it has the highest risk of leaks.
- Keep them with a lower score. The detector reports the span with a confidence value, and a later step decides what to do.
- Use context. A candidate that fails Luhn but sits next to the word "card" or "visa" is probably a mistyped card number.
Here is a version that combines options 2 and 3:
CONTEXT_RE = re.compile(r"\b(?:card|visa|mastercard|amex|cvv|expir\w*)\b", re.I)
def find_cards_scored(text, window=30):
results = []
for m in CARD_RE.finditer(text):
if luhn_valid(m.group()):
score = 0.95
else:
nearby = text[max(0, m.start() - window): m.end() + window]
score = 0.5 if CONTEXT_RE.search(nearby) else 0.0
if score > 0:
results.append((m.start(), m.end(), "CREDIT_CARD", score))
return results
print(find_cards_scored("My card is 4111 1111 1111 1112, order 1234567890123"))The output is:
[(11, 30, 'CREDIT_CARD', 0.5)]The mistyped card number is kept at score 0.5 because the word "card" is nearby. The order number is dropped, because it fails Luhn and has no card word within 30 characters. The word "order" is not in the context list.
The scored tuples have four fields, while earlier detectors return three. The next chapters on combining detectors cover how to merge spans and scores. For now, remember that a validator can output a confidence level instead of a yes/no decision.
Edge cases to test
- Length. Luhn on a 6-digit string is meaningless. Always enforce a length range before or inside the validator, as
luhn_validdoes. - Separators. Strip spaces and hyphens before checking. The code does this by keeping only characters where
c.isdigit()is true. Note thatstr.isdigit()is true for some non-ASCII digits, such as superscripts. If your input may contain these, usec in "0123456789"instead. - Repeated digits.
0000 0000 0000 0000passes Luhn, because every digit is zero. If you see such values in your data, add a rule to reject them. - Issuer prefix. Real card numbers begin with known prefixes (for example, 4 for Visa and 51 to 55 for Mastercard). Checking the prefix removes more false positives, at the cost of missing new issuer ranges as they appear.
- Longer strings. A 20-digit ID that contains a Luhn-valid 16-digit run is not matched, because
\brequires a word boundary at both ends. This is the right behavior here, but it means card numbers glued to other digits are missed.
Summary of the technique
- Use a broad regex to find candidates, and a validator to reject impossible ones.
- Luhn removes about 90% of random digit strings. IBAN's mod-97 check removes about 99%.
- A passing checksum means the value could be an identifier. It does not prove the value is real or in use.
- Decide what to do with failed candidates. Dropping them is simple, and keeping them with a low score is safer for privacy.
Exercise
A regex finds the 16-digit string 5500 0000 0000 0004 and 1234 5678 9012 3456 in a support ticket. The first passes Luhn and the second fails. Your team's rule is to drop any candidate that fails the checksum. Name one situation where dropping the second candidate causes a privacy leak, and one change that reduces the risk.
Show answer
If the user mistyped one digit of a real card number, the value fails Luhn but still exposes 15 correct digits. Dropping it leaks nearly the whole number. A fix is to keep failed candidates with a lower confidence score when a context word such as "card" appears near them, and redact them when the score passes a threshold.
Exercise
Estimate how many of 10,000 random 16-digit order IDs would be reported as card numbers by a detector that uses only the regex and the Luhn check. Then say what extra check would reduce that number further.
Show answer
About 1,000, because roughly 1 in 10 random digit strings passes Luhn. Checking that the number starts with a known issuer prefix (such as 4, or 51 to 55) would remove most of the remainder, since random IDs rarely begin with those prefixes.
Exercise
The IBAN validator above uses s.isascii() before calling int(c, 36). What would go wrong without that check?
Show answer
int(c, 36) raises a ValueError for characters outside the digits and ASCII letters, such as accented letters. s.isalnum() returns true for those characters, so a string containing one would crash the detector instead of returning False.