Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard Pattern Matching:

Tags:

xcode

swift

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

like image 760
Raheel Avatar asked Mar 04 '23 15:03

Raheel


1 Answers

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
like image 160
Martin R Avatar answered Apr 02 '23 14:04

Martin R