Here slightly edited code from one of my earliest posts to DaniWeb. Limitted by recursion limit of Python as it uses recursion, but interesting for me.
Recursive matching of wildcard string
""" 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[0] == '*':
return any(match_pat(pattern[1:],mystring[index:]) for index in range(len(mystring)))
elif pattern[0] == '?':
return match_pat(pattern[1:],mystring[1:])
else:
return pattern[0] == mystring[0] 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)
Gribouillis 1,391 Programming Explorer Team Colleague
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.