Algorithmspattern matching with conditions
Pattern Matching With Conditions (Wildcards and Rules)
TT
Testlaa Team
May 14, 2026•1 min read
Conditional matching means not every character must be equal—wildcards, case-insensitive rules, or predicates like vowel matches consonant. Model allowed pairs explicitly instead of ad-hoc branches.
Why this shows up in the real world
Fuzzy SKU matchers allow ? for unknown characters. Password rules check patterns with mixed constraints per position.
Core idea (explained for students)
Write match(a, b) -> bool encapsulating rules, then scan both strings with two pointers or nested alignment checks. For *-style glob patterns, recursion or DP on segments is common.
Try this in Python
def matches_wild(s: str, p: str) -> bool:
# single ? wildcard same length only (illustrative)
if len(s) != len(p):
return False
return all(pc == "?" or sc == pc for sc, pc in zip(s, p))
print(matches_wild("ab1", "a?1"))
Common mistakes
- Greedy
*matching can be wrong—classic regex lesson. - Mixing
==with casefold forgetting to normalize both sides.
Key takeaways
- Encode rules in one table or function so tests stay readable.
- Start with brute force on small alphabets before optimizing.
Tags:
StringsPythonStudents
