Wildcard Matching Implementation in Rust
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 your String Algorithms question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Wildcard Matching runs in O(n*m) time and O(n*m) space, in Rust as in every other language.
- ✓std has no glob matcher, so the ecosystem answer is one of two crates. glob gives you glob::Pattern::new(&str) -> Result<Pattern, PatternError> and Pattern::matches(&str) -> bool, plus matches_with(name, MatchOptions) whose fields case_sensitive, require_literal_separator and require_literal_leading_dot let you pick shell semantics explicitly.
- ✓Take &str, never String, and return bool or Result rather than panicking on a bad pattern.
- ✓The Rust trap: Working over bytes is fast and correct for ASCII patterns, but the moment you index a String by a computed range the program panics: &s[i..i + 1] aborts with 'byte index is not a char boundary' on any multi-byte character, and it is a runtime panic, not a compile error, so it ships.
- ✓Each prev[j] and cur[j] is a checked index; iterating slices or using get_unchecked in a verified inner loop lets LLVM drop those checks, and the win is real because the loop body is otherwise two comparisons.
What Wildcard Matching actually is
Wildcard Matching in Rust: what you actually reach for
Rust implementation
pub fn is_match(s: &str, p: &str) -> bool {
let sb = s.as_bytes();
let pb = p.as_bytes();
let m = pb.len();
let mut prev = vec![false; m + 1];
let mut cur = vec![false; m + 1];
prev[0] = true;
for j in 1..=m {
prev[j] = prev[j - 1] && pb[j - 1] == b'*';
}
for &sc in sb {
cur[0] = false;
for j in 1..=m {
cur[j] = match pb[j - 1] {
b'*' => cur[j - 1] || prev[j],
b'?' => prev[j - 1],
c => c == sc && prev[j - 1],
};
}
std::mem::swap(&mut prev, &mut cur);
}
prev[m]
}
// crate route, when you need shell semantics:
// let pat = glob::Pattern::new("src/*.rs")?;
// assert!(pat.matches("src/lib.rs"));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 Rust-specific trap
Performance in Rust, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Wildcard Matching?
std has no glob matcher, so the ecosystem answer is one of two crates. glob gives you glob::Pattern::new(&str) -> Result<Pattern, PatternError> and Pattern::matches(&str) -> bool, plus matches_with(name, MatchOptions) whose fields case_sensitive, require_literal_separator and require_literal_leading_dot let you pick shell semantics explicitly. globset, the matcher inside ripgrep, is the one to reach for when you test many patterns: Glob::new("*.rs")?.compile_matcher() yields a GlobMatcher, and GlobSetBuilder compiles a whole rule set into one matcher that partitions the globs into literal, required-extension, prefix/suffix and Aho-Corasick base-name strategies with a RegexSet for the leftovers, so a single pass answers all of them.
What is the most common Rust mistake when implementing Wildcard Matching?
Working over bytes is fast and correct for ASCII patterns, but the moment you index a String by a computed range the program panics: &s[i..i + 1] aborts with 'byte index is not a char boundary' on any multi-byte character, and it is a runtime panic, not a compile error, so it ships. Reaching for .chars() instead removes the panic and introduces a silent one: .chars().nth(i) walks from the start every call, so an O(n*m) DP written with it is really O(n^2*m) and the borrow checker, clippy and the type system all approve. Collect once into Vec<char> if you need character semantics.
How does Wildcard Matching actually perform in Rust?
Each prev[j] and cur[j] is a checked index; iterating slices or using get_unchecked in a verified inner loop lets LLVM drop those checks, and the win is real because the loop body is otherwise two comparisons. Vec<bool> stores one byte per element, not one bit, so a 4096-wide row is 4 KiB and stays in L1; bit packing needs the bitvec crate and usually loses here on shift cost. Measure in release only: debug builds keep every bounds check, skip inlining and add overflow checks, which routinely makes this matcher an order of magnitude slower than the optimised build. 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 trialStudying for this? Replit free tiers and academic plans are laid out 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.