Search code examples
algorithmpseudocode

An algorithm that return true if a given string match a given pattern


Anyone has an idea of how to implement an algorithm finding if string match a specific pattern?( not contains it!) without the use of regular expression...

Rules are,the pattern can hold sign like ? or *:
? = one character or number
* = multiple characters or number or non at all

For example:

isMatching("??Ab", "cbAb") return true.
isMatching("*a?Ab", "123cacAbAAb") return false.
isMatching("*a?Ab", "123aaAb") return true.
isMatching("*a?Ab", "007aaabAb") return true.

isMatching("a?D*", "arD1324687e") return true.


Solution

  • Some type of recursion would be simple enough:

    def match(pattern, str):
        return match_(pattern, str)
    
    def match_(pattern, str)
       if len(pattern) == 0 and len(str) == 0:
           return True
    
       switch pattern[0]:
           case '?':
                match_(pattern[1: ], str[1: ])
           case '*':
                return match_(pattern, str[1: ]) or match_(pattern[1: ], str[1: ]) or match_(pattern[1: ], str)
           default:
                return pattern[0] == str[0] and match_(pattern[1: ], str[1: ])