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

Wildcard Matching Implementation in Go

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 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 Go as in every other language.
  • ✓path/filepath.Match(pattern, name string) (bool, error) is the built-in, with path.Match for slash-separated strings that are not filesystem paths.
  • ✓Return (bool, error) and let the caller decide; do not panic on a bad pattern. Reviewers want one flat []bool indexed as i*(m+1)+j, or two swapped rows, rather than a [][]bool that allocates a slice header and a backing array per row.
  • ✓The Go trap: matched, _ := filepath.Match(pat, name) is the bug. A typo like "[a-z" is not a pattern that matches nothing, it is ErrBadPattern, and with the error dropped your allow-list silently denies everything or your deny-list silently permits everything, with no log line anywhere.
  • ✓A [][]bool costs one allocation per row plus a pointer dereference on every cell; one flat []bool is a single allocation and keeps the whole table linear in memory, which matters once rows exceed the cache line.

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 Go: what you actually reach for

path/filepath.Match(pattern, name string) (bool, error) is the built-in, with path.Match for slash-separated strings that are not filesystem paths. Two documented limits decide whether you can use it: '*' never matches the separator, and there is no recursive '**', so filepath.Match("a/*", "a/b/c") is false by design. Malformed patterns, an unterminated '[' for instance, return filepath.ErrBadPattern. On Windows, filepath.Match treats '\\' as the separator rather than as an escape. filepath.Glob walks the filesystem with the same grammar, and regexp gives you RE2, whose linear-time guarantee removes any catastrophic-backtracking risk.

Go implementation

Return (bool, error) and let the caller decide; do not panic on a bad pattern. Reviewers want one flat []bool indexed as i*(m+1)+j, or two swapped rows, rather than a [][]bool that allocates a slice header and a backing array per row. They want the byte form s[i] rather than converting to []byte or []rune when the pattern is ASCII, and they will reject any code path that discards the error from filepath.Match.
go
package wildcard

import "path/filepath"

func IsMatch(s, p string) bool {
	m := len(p)
	prev := make([]bool, m+1)
	cur := make([]bool, m+1)
	prev[0] = true
	for j := 1; j <= m; j++ {
		prev[j] = prev[j-1] && p[j-1] == '*'
	}
	for i := 0; i < len(s); i++ {
		cur[0] = false
		for j := 1; j <= m; j++ {
			switch p[j-1] {
			case '*':
				cur[j] = cur[j-1] || prev[j]
			case '?':
				cur[j] = prev[j-1]
			default:
				cur[j] = p[j-1] == s[i] && prev[j-1]
			}
		}
		prev, cur = cur, prev
	}
	return prev[m]
}

// Stdlib route: always handle the error.
func Glob(pattern, name string) (bool, error) {
	return filepath.Match(pattern, name)
}

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 Go-specific trap

matched, _ := filepath.Match(pat, name) is the bug. A typo like "[a-z" is not a pattern that matches nothing, it is ErrBadPattern, and with the error dropped your allow-list silently denies everything or your deny-list silently permits everything, with no log line anywhere. The second Go-shaped trap is index space: for i, c := range s yields i as a byte offset and c as a rune, while len(s) and s[i] are byte counts and bytes, so a DP that ranges over the input but sizes its rows with len advances i by two or three on the first non-ASCII character and reads a stale cell.

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

A [][]bool costs one allocation per row plus a pointer dereference on every cell; one flat []bool is a single allocation and keeps the whole table linear in memory, which matters once rows exceed the cache line. A make([]bool, m+1) with a non-constant length always heap-allocates through runtime.makeslice: escape analysis can only stack-allocate a slice whose length is a compile-time constant and small, so these rows land on the heap even though they never leave the function. Verify with go build -gcflags=-m, and reuse a sync.Pool or a caller-supplied scratch slice if the matcher is hot. filepath.Match has no compiled form and re-parses the pattern on every call, so in a hot loop translate once into a regexp.Regexp with regexp.MustCompile and reuse it. 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 applies wherever its problem shape appears in your own code. In Go, check whether the standard library or a well maintained package already provides it before you write your own. 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 Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Wildcard Matching?

path/filepath.Match(pattern, name string) (bool, error) is the built-in, with path.Match for slash-separated strings that are not filesystem paths. Two documented limits decide whether you can use it: '*' never matches the separator, and there is no recursive '**', so filepath.Match("a/*", "a/b/c") is false by design. Malformed patterns, an unterminated '[' for instance, return filepath.ErrBadPattern. On Windows, filepath.Match treats '\\' as the separator rather than as an escape. filepath.Glob walks the filesystem with the same grammar, and regexp gives you RE2, whose linear-time guarantee removes any catastrophic-backtracking risk.

What is the most common Go mistake when implementing Wildcard Matching?

matched, _ := filepath.Match(pat, name) is the bug. A typo like "[a-z" is not a pattern that matches nothing, it is ErrBadPattern, and with the error dropped your allow-list silently denies everything or your deny-list silently permits everything, with no log line anywhere. The second Go-shaped trap is index space: for i, c := range s yields i as a byte offset and c as a rune, while len(s) and s[i] are byte counts and bytes, so a DP that ranges over the input but sizes its rows with len advances i by two or three on the first non-ASCII character and reads a stale cell.

How does Wildcard Matching actually perform in Go?

A [][]bool costs one allocation per row plus a pointer dereference on every cell; one flat []bool is a single allocation and keeps the whole table linear in memory, which matters once rows exceed the cache line. A make([]bool, m+1) with a non-constant length always heap-allocates through runtime.makeslice: escape analysis can only stack-allocate a slice whose length is a compile-time constant and small, so these rows land on the heap even though they never leave the function. Verify with go build -gcflags=-m, and reuse a sync.Pool or a caller-supplied scratch slice if the matcher is hot. filepath.Match has no compiled form and re-parses the pattern on every call, so in a hot loop translate once into a regexp.Regexp with regexp.MustCompile and reuse it. 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

Most AI and dev tools have a student plan. See which ones and how to claim them 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

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.