/
wildcard.go
40 lines (34 loc) · 881 Bytes
/
wildcard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package pufferpanel
import (
"regexp"
"strings"
)
func CompareWildcard(source, match string) bool {
if match == "" || match == "*" {
return true
}
if strings.Contains(match, "*") {
regex := WildCardToRegexp(match)
return matchRegex(regex, source)
} else {
return source == match
}
}
// WildCardToRegexp converts a wildcard pattern to a regular expression pattern.
func WildCardToRegexp(pattern string) string {
var result strings.Builder
for i, literal := range strings.Split(pattern, "*") {
// Replace * with .*
if i > 0 {
result.WriteString(".*")
}
// Quote any regular expression meta characters in the
// literal text.
result.WriteString(regexp.QuoteMeta(literal))
}
return result.String()
}
func matchRegex(pattern string, value string) bool {
result, _ := regexp.MatchString("^"+WildCardToRegexp(pattern)+"$", value)
return result
}