""" Recursive matching of wildcard pattern """ from __future__ import print_function def match_pat(pattern, mystring): """ find if pattern match mystring, wildcards: * any string of characters (possibly empty), ? single required characters """ #print ("%r vs %r" % (pattern, mystring)) if not pattern: return not mystring elif pattern == '*': return True elif not mystring: return False elif pattern == '*': return any(match_pat(pattern[1:],mystring[index:]) for index in range(len(mystring))) elif pattern == '?': return match_pat(pattern[1:],mystring[1:]) else: return pattern == mystring and match_pat(pattern[1:], mystring[1:]) if __name__ == '__main__': for pat in 'a*at*r*', '*a??a*','*a*?r*': for word in ("anteater",'albatross','albania', 'samba'): print(word, pat, match_pat(pat,word)) print('-'*30)
Are you able to help answer this sponsored question?
Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.