Recursive matching of wildcard string

TrustyTony

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.

807 Views
About the Author

IT Pro doing Eng-Fin-Eng translations

""" 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)

Interesting, but why not use module fnmatch ?

This was response to thread, where student was required to produce one themself. I thought maybe it is of interest for somebody learning to understand recursion.

Good for you to mention what is there at standard library, additionally there is similar things in modules re and glob (but glob uses fnmatch, if I remember correctly, and fnmatch is using re after massaging the input format).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.