41 lines
1.1 KiB
Swift
41 lines
1.1 KiB
Swift
import Foundation
|
|
|
|
public enum WildcardMatcher {
|
|
/// Matches a string against a glob pattern with `*` (zero or more chars) and `?` (single char).
|
|
public static func matches(_ string: String, pattern: String) -> Bool {
|
|
let s = Array(string.lowercased())
|
|
let p = Array(pattern.lowercased())
|
|
return matchHelper(s, 0, p, 0)
|
|
}
|
|
|
|
private static func matchHelper(_ s: [Character], _ si: Int, _ p: [Character], _ pi: Int) -> Bool {
|
|
var si = si
|
|
var pi = pi
|
|
var starIdx = -1
|
|
var matchIdx = 0
|
|
|
|
while si < s.count {
|
|
if pi < p.count && (p[pi] == "?" || p[pi] == s[si]) {
|
|
si += 1
|
|
pi += 1
|
|
} else if pi < p.count && p[pi] == "*" {
|
|
starIdx = pi
|
|
matchIdx = si
|
|
pi += 1
|
|
} else if starIdx != -1 {
|
|
pi = starIdx + 1
|
|
matchIdx += 1
|
|
si = matchIdx
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
|
|
while pi < p.count && p[pi] == "*" {
|
|
pi += 1
|
|
}
|
|
|
|
return pi == p.count
|
|
}
|
|
}
|