Match a Simple Pattern Without Regex in Go

For one of my projects, gocache, I had to find a way to filter all keys in a map that matched a simple pattern.

Unfortunately, Go’s regex implementation isn’t known for its speed, and all I needed to support was the wildcard asterisk (that’s what I meant by simple pattern).

While implementing a wildcard pattern matching algorithm isn’t necessarily overly complicated, implementing a good one would require some time, so like any programmer would, I used a trusty search engine and did my research before reinventing the wheel for an umpteenth time.

A lot of implementations were good, but none of the results I found made me happy as this one:

filepath.Match(pattern, s)

That’s right, why bother implementing something that already exists in the standard library?

So this function is all it took to fulfil my use case:

import "path/filepath"

// MatchPattern checks whether a string matches a pattern
func MatchPattern(pattern, s string) bool {
	if pattern == "*" {
		return true
	}
	matched, _ := filepath.Match(pattern, s)
	return matched
}

As simple as that.