Sub topic 6
Exact, fuzzy, phonetic, and token-based name matching
What this chapter assumes
You should know why a firm screens customers against sanctions lists and how names are normalized before comparison (lowercase, accents removed, punctuation stripped, whitespace collapsed). You should also be able to read short Python functions. This chapter covers the four families of comparison that turn two normalized names into a decision or a score. The next chapter covers how to pick thresholds for those scores.
No single method is enough. Each one catches errors the others miss, and each fails in a predictable way. Production screening engines combine several of them. Knowing what each one can and cannot do tells you why an alert fired, or why one did not.
Exact matching
Exact matching checks whether two normalized strings are identical. It is cheap and easy to explain to an auditor. It is also the right first check for identifiers such as passport numbers, vessel IMO numbers, and registration numbers, where a near miss means a different object.
For names, exact matching on its own is weak. Spelling differs between documents, and list entries often include aliases that the customer record lacks. An exact match on a normalized name is still worth keeping as a separate signal. It identifies the strongest alerts, and a reviewer can see right away that no fuzziness was needed.
Exact matching also fails in a quiet way when normalization is wrong. If one system strips the apostrophe in "O'Brien" to nothing ("obrien") and another replaces it with a space ("o brien"), the two never match. Both sides of every comparison must use the same normalization code.
Edit distance and similarity ratios
Fuzzy matching tolerates small spelling differences. The usual building block is the Levenshtein distance, which counts the fewest single-character insertions, deletions, and substitutions needed to turn one string into another. "mohammed" becomes "mohamed" with one deletion, so the distance is 1.
def levenshtein(a: str, b: str) -> int:
"""Minimum number of single-character edits to turn a into b."""
previous = list(range(len(b) + 1))
for i, ca in enumerate(a, start=1):
current = [i]
for j, cb in enumerate(b, start=1):
current.append(
min(
previous[j] + 1, # deletion
current[j - 1] + 1, # insertion
previous[j - 1] + (ca != cb), # substitution
)
)
previous = current
return previous[-1]
def edit_similarity(a: str, b: str) -> float:
"""Distance rescaled to 0.0 (nothing shared) through 1.0 (identical)."""
longest = max(len(a), len(b))
if longest == 0:
return 1.0
return 1.0 - levenshtein(a, b) / longest
print(levenshtein("mohammed", "mohamed"))
print(round(edit_similarity("mohammed", "mohamed"), 2))
print(round(edit_similarity("li", "lu"), 2))The raw distance is a poor way to set a policy, because one edit means different things at different lengths. One edit in "mohammed" leaves 88% of the characters intact. One edit in "li" leaves 50%. This is why the function divides by the longer length and returns a ratio. A rule such as "distance of 2 or less" will over-alert on short names and under-alert on long ones.
Several variants are common:
- Damerau-Levenshtein also counts a swap of two adjacent characters as one edit. This fits typing errors like "Hasan" and "Hasna".
- Jaro-Winkler weights agreement at the start of the string more heavily. It was designed for personal names and is often more forgiving than Levenshtein of differences near the end of a name.
- Python's
difflib.SequenceMatcheruses a different algorithm based on the longest common blocks. It is in the standard library and fine for learning, but it is not a drop-in replacement for the other measures. Its scores will not match those from a commercial engine.
When someone quotes "an 85% match", always ask which algorithm produced it. The same name pair can score 0.78 under one measure and 0.93 under another.
Phonetic matching
Phonetic algorithms reduce a name to a short code based on how it sounds, so that names spelled differently can share the same code. Soundex is the classic example. It keeps the first letter and replaces the following consonants with digits, giving a four-character code. "Smith" and "Smyth" both become S530.
import re
def soundex(word: str) -> str:
"""American Soundex for an ASCII word. Returns '' if there are no letters."""
groups = {"bfpv": "1", "cgjkqsxz": "2", "dt": "3", "l": "4", "mn": "5", "r": "6"}
codes = {letter: digit for letters, digit in groups.items() for letter in letters}
letters = [c for c in word.lower() if c.isascii() and c.isalpha()]
if not letters:
return ""
result = letters[0].upper()
previous = codes.get(letters[0], "")
for ch in letters[1:]:
code = codes.get(ch, "")
if code and code != previous:
result += code
if ch not in "hw": # h and w do not break a run of equal codes
previous = code
if len(result) == 4:
break
return result.ljust(4, "0")
def phonetic_key(name: str) -> str:
"""Order-independent key: sorted Soundex codes of each word."""
tokens = re.findall(r"[a-z]+", name.lower())
return " ".join(sorted(soundex(t) for t in tokens))
print(soundex("Mohammed"), soundex("Mohamed"), soundex("Muhammad"))
print(soundex("Smith"), soundex("Smyth"))
print(phonetic_key("Mohammed Al-Sayed") == phonetic_key("Al Sayed, Mohamed"))All three spellings of Mohammed produce M530, which is the case where edit distance struggles and phonetics shines. Phonetic keys have clear limits:
- English bias. Soundex was built for English surnames. It assumes Latin letters and English pronunciation. Names transliterated from Arabic, Chinese, or Cyrillic follow other sound patterns, and the code can group unrelated names or separate related ones.
- Coarse buckets. Many different names share a code. A phonetic match is a reason to look closer. It is rarely strong evidence on its own.
- Early errors are costly. The first letter is kept as written. "Catherine" and "Katherine" get different codes (C365 and K365) even though they sound the same.
- Short codes lose information. Four characters cannot distinguish long names that start alike.
Better-known successors include Metaphone and Double Metaphone, and many engines add language-specific phonetic rules or transliteration tables. The idea is the same: trade precision for recall on spelling variation.
Token-based matching
Names are made of parts, and the parts do not always come in the same order. Lists often record "Al-Sayed, Mohamed" while a customer file holds "Mohammed Al Sayed". Character-level comparison of the full strings would give a low score for what is the same person.
Token-based methods split each name into words first. Two common approaches:
- Token sort. Sort the words alphabetically, rejoin them, and then run a character-level comparison. This handles reordering and also keeps the tolerance for small spelling changes.
- Token set. Compare the shared words against the unshared words, so that an extra middle name on one side does not drag the score down much.
import re
import unicodedata
from difflib import SequenceMatcher
def normalize(name: str) -> str:
decomposed = unicodedata.normalize("NFKD", name)
no_accents = "".join(c for c in decomposed if not unicodedata.combining(c))
no_punct = re.sub(r"[^\w\s]", " ", no_accents.casefold())
return " ".join(no_punct.split())
def token_sort_score(a: str, b: str) -> float:
"""Similarity from 0.0 to 1.0, ignoring word order."""
ta = " ".join(sorted(normalize(a).split()))
tb = " ".join(sorted(normalize(b).split()))
return SequenceMatcher(None, ta, tb).ratio()
print(round(token_sort_score("Mohammed Al-Sayed", "Al Sayed, Mohamed"), 2))
print(round(token_sort_score("Mohammed Al-Sayed", "Jane Doe"), 2))
print(round(token_sort_score("Ali Hassan", "Hassan Ali"), 2))The first pair scores about 0.97, because after sorting the strings differ by one character. The last pair scores 1.0. That is the main hazard of token sorting. In many naming systems the order carries meaning, and "Ali Hassan" and "Hassan Ali" can be two different people, one with the given name Ali and one with Hassan. Token methods raise recall and also raise false positives, which is why a date of birth or other identifier is needed to separate the cases.
Comparing the four families
| Method | Catches | Typically misses | Typical failure |
|---|---|---|---|
| Exact | Identical normalized names and identifiers | Any spelling variant, alias, or reordering | Missed matches when normalization differs |
| Edit distance | Typos, dropped or doubled letters | Reordered parts, different transliterations | Unfair on short names if a raw distance is used |
| Phonetic | Spellings that sound alike | Differences in the first letter, non-English sound patterns | Large buckets of unrelated names |
| Token-based | Reordered parts, extra or missing middle names | Spelling variation inside tokens, unless combined with fuzzy scoring | Matches swapped given and family names |
Combining signals
Screening systems rarely rely on one measure. A common design takes the best score across several comparisons, or a weighted score, and also records which comparisons contributed. A few design points matter in practice:
- Compare against every alias. A list entry has a primary name and often many alternative names. Score each one, and keep the highest.
- Compare name parts, not only whole strings. A strong match on a rare family name is more telling than a match on a common given name such as "Mohammed". Some engines weight tokens by how rare they are in the data.
- Keep the reason with the score. An alert should say "token sort 0.97 against alias X" rather than only "0.97", so a reviewer can judge it quickly.
- Use blocking to stay fast. Comparing every customer against every list entry with edit distance is slow. Engines first narrow the candidates, for example by phonetic key or shared rare tokens, and then score only those pairs. Be aware that a blocking step can itself drop a true match. Its rules need testing like any other control.
Common errors
- Comparing un-normalized strings. Case, accents, and punctuation create false misses that no fuzzy score should be asked to fix.
- Treating a score as a probability. A score of 0.9 does not mean a 90% chance of a true match. It is a similarity value whose meaning depends on the algorithm and the data.
- Using one global threshold for all name types. Person names, company names, and vessel names behave differently. Company names include generic words such as "trading", "limited", and "holdings", which inflate similarity without indicating identity.
- Ignoring short and very common names. These produce many alerts with little information. They need a policy, such as requiring a second identifier before an alert is raised.
- Skipping non-Latin scripts. If the list holds names in Arabic or Cyrillic script and the customer file holds Latin transliterations, character-level and Soundex comparisons only work after transliteration. Decide how that step is done and test it.
Exercises
Exercise
The normalized names "sayed" and "sayid" differ by one substituted letter. Using the edit_similarity function from this chapter, what score do they receive, and why is the score lower than for "mohammed" and "mohamed" even though both pairs differ by one edit?
Show answer
levenshtein("sayed", "sayid") is 1 and the longer string has 5 characters, so the similarity is 1 - 1/5 = 0.8. For "mohammed" and "mohamed" the distance is also 1, but the longer string has 8 characters, so the score is 1 - 1/8 = 0.875. The same single edit weighs more on a shorter name, which is why raw edit distances are an unfair basis for a rule.
Exercise
A customer named "Hassan Ali" gets a token-sort score of 1.0 against a listed individual "Ali Hassan". Name one reason this could be a false positive and one piece of information a reviewer would use to decide.
Show answer
Token sorting ignores word order, so it cannot tell the given name from the family name. "Hassan Ali" and "Ali Hassan" can be different people. A reviewer would compare secondary identifiers such as date of birth, nationality, or an ID number, and would record the result and reasoning in the alert disposition.