Wildcard Matching Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Wildcard Matching runs in O(n*m) time and O(n*m) space, in Python as in every other language.
- ✓The batteries are in fnmatch: fnmatch.fnmatch(name, pat), fnmatch.fnmatchcase(name, pat), fnmatch.filter(names, pat) and fnmatch.translate(pat), which returns a regex source string you feed to re.compile.
- ✓Reviewers ask why you hand-rolled a matcher at all when fnmatch.translate plus re gives you a C-speed engine.
- ✓The Python trap: fnmatch.fnmatch runs both arguments through os.path.normcase first. On Linux that is the identity, so your tests pass; on Windows it lowercases everything, so 'README*' silently matches 'readme.txt' and a case-sensitive rule you shipped stops being case-sensitive on one platform.
- ✓Every cell of the DP costs an interpreter dispatch, so a pure-Python O(n*m) fill runs roughly two orders of magnitude slower than the equivalent C loop; for patterns reused across many names, fnmatch.translate plus a compiled re object moves the inner loop into C and usually wins outright.
What Wildcard Matching actually is
Wildcard Matching in Python: what you actually reach for
Python implementation
from fnmatch import fnmatchcase
def is_match(s: str, p: str) -> bool:
n, m = len(s), len(p)
prev = [False] * (m + 1)
prev[0] = True
for j in range(1, m + 1):
prev[j] = prev[j - 1] and p[j - 1] == "*"
for i in range(1, n + 1):
cur = [False] * (m + 1)
sc = s[i - 1]
for j in range(1, m + 1):
pc = p[j - 1]
if pc == "*":
cur[j] = cur[j - 1] or prev[j]
elif pc == "?" or pc == sc:
cur[j] = prev[j - 1]
prev = cur
return prev[m]
# stdlib route, case-sensitive on every OS:
assert fnmatchcase("report.txt", "re*.txt")
assert not fnmatchcase("README.txt", "re*.txt")Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Wildcard Matching?
The batteries are in fnmatch: fnmatch.fnmatch(name, pat), fnmatch.fnmatchcase(name, pat), fnmatch.filter(names, pat) and fnmatch.translate(pat), which returns a regex source string you feed to re.compile. fnmatch's grammar is bigger than '?' and '*' alone: it also honours [seq] and [!seq] character classes. pathlib.PurePath.match applies the same engine with path-component semantics. Internally fnmatch memoises the translated regex, so repeated calls with the same pattern do not re-translate. For directory walking, glob.glob and glob.iglob wrap the same syntax with filesystem semantics.
What is the most common Python mistake when implementing Wildcard Matching?
fnmatch.fnmatch runs both arguments through os.path.normcase first. On Linux that is the identity, so your tests pass; on Windows it lowercases everything, so 'README*' silently matches 'readme.txt' and a case-sensitive rule you shipped stops being case-sensitive on one platform. Use fnmatchcase. The second trap is recursive memoised matching: s[i:] slices copy, turning each call into O(n) work and the whole matcher into O(n^2*m), and the recursion itself hits the default limit near a thousand frames and raises RecursionError on long inputs, not a wrong answer but a crash.
How does Wildcard Matching actually perform in Python?
Every cell of the DP costs an interpreter dispatch, so a pure-Python O(n*m) fill runs roughly two orders of magnitude slower than the equivalent C loop; for patterns reused across many names, fnmatch.translate plus a compiled re object moves the inner loop into C and usually wins outright. Two rolling lists beat a list-of-lists: you avoid n row objects and the pointer chase. Local-variable binding matters here, but only builtins cost LOAD_GLOBAL: bind _len = len once if you call it inside a loop. p and s are parameters already, so they compile to LOAD_FAST and hoisting them buys nothing; hoisting the current character out of the inner loop still pays, because it turns a repeated subscript into a single local read. Time complexity is O(n*m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.