Wildcard Pattern Matching: Given a string and a pattern containing wildcard characters i.e. *
and ?
, where ?
can match to any single character in the input string and *
can match to any number of characters including zero characters, design an efficient algorithm to find if the pattern matches with the complete input string or not.
For example:
Input: string = "xyxzzxy", pattern = "x***y"
Output: Match
Input: string = "xyxzzxy", pattern = "x***x"
Output: No Match
Input: String = "xyxzzxy", pattern = "x***x?"
Output: Match
Input: String = "xyxzzxy", pattern = "*"
Output: Match
With the help of Foundation classes (in particular NSPredicate
) you can implement wildcard matching simply as
func wildcard(_ string: String, pattern: String) -> Bool {
let pred = NSPredicate(format: "self LIKE %@", pattern)
return !NSArray(object: string).filtered(using: pred).isEmpty
}
The LIKE comparison does exactly what you want:
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.
Examples:
print(wildcard("xyxzzxy", pattern: "x***y")) // true
print(wildcard("xyxzzxy", pattern: "x***x")) // false
print(wildcard("xyxzzxy", pattern: "x***x?")) // true
print(wildcard("xyxzzxy", pattern: "*")) // true
print(wildcard("a12b34c", pattern: "a?b?c")) // false
print(wildcard("a12b34c", pattern: "a*b*c")) // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With