yq/pkg/yqlib/matchKeyString.go

59 lines
1.2 KiB
Go
Raw Permalink Normal View History

2020-11-03 23:48:43 +00:00
package yqlib
2020-10-08 23:59:03 +00:00
func matchKey(name string, pattern string) (matched bool) {
2020-10-08 23:59:03 +00:00
if pattern == "" {
return name == pattern
}
log.Debug("pattern: %v", pattern)
if pattern == "*" {
log.Debug("wild!")
return true
}
return deepMatch(name, pattern)
2020-10-08 23:59:03 +00:00
}
// deepMatch reports whether the name matches the pattern in linear time.
// Source https://research.swtch.com/glob
func deepMatch(name, pattern string) bool {
px := 0
nx := 0
nextPx := 0
nextNx := 0
for px < len(pattern) || nx < len(name) {
if px < len(pattern) {
c := pattern[px]
switch c {
default: // ordinary character
if nx < len(name) && name[nx] == c {
px++
nx++
continue
}
case '?': // single-character wildcard
if nx < len(name) {
px++
nx++
continue
}
case '*': // zero-or-more-character wildcard
// Try to match at nx.
// If that doesn't work out,
// restart at nx+1 next.
nextPx = px
nextNx = nx + 1
px++
continue
2020-10-08 23:59:03 +00:00
}
}
// Mismatch. Maybe restart.
if 0 < nextNx && nextNx <= len(name) {
px = nextPx
nx = nextNx
continue
}
return false
2020-10-08 23:59:03 +00:00
}
// Matched all of pattern to all of name. Success.
return true
2020-10-08 23:59:03 +00:00
}