Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Wildcard Matching Implementation in Rust

14 min readintermediate
Website QA and SEO audits

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 decides whether a whole string is described by a pattern in which '?' stands for exactly one character and '*' stands for any run of characters, including none. It is a full-string test, not a search: 'a*c' matches 'abbbc' but not 'xabbbc'. Engineers hit it writing file globs, log filters, ACL and route rules, and CDN purge patterns. The textbook solution is a dynamic-programming table dp[i][j] = 'does s[0..i) match p[0..j)', filled in O(n*m) time; a greedy two-pointer with one backtrack point is the usual production shortcut.

Wildcard Matching in Rust: what you actually reach for

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.

Rust implementation

Take &str, never String, and return bool or Result rather than panicking on a bad pattern. Reviewers insist you hoist s.as_bytes() and p.as_bytes() once and index the slices, and they will flag .chars().nth(i) on sight. Two rolling Vec<bool> rows swapped with std::mem::swap are preferred over Vec<Vec<bool>>, which is one heap allocation per row. Public matchers are expected to document whether '?' means one byte or one char.
rust
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 Free

The Rust-specific 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. 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.

Performance in Rust, beyond the O(n*m)

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. The asymptotic cost is the same in every language, O(n*m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Wildcard Matching between languages.

Real-World Applications

Wildcard Matching is used extensively in production software: database engines, compilers, operating systems, and application frameworks all use Wildcard Matching internally. In Rust specifically, crates in the ecosystem leverage this for systems programming. Understanding Wildcard Matching helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Wildcard Matching appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Wildcard Matching over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Wildcard Matching to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

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.