Recursive matching of wildcard string

Updated TrustyTony 0 Tallied Votes 1K Views Share

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 pattern

from __future__ import print_function

def match_pat(pattern, mystring):
    """ find if pattern match mystring,
            * 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:])
        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))
Gribouillis 1,391 Programming Explorer Team Colleague

Interesting, but why not use module fnmatch ?

TrustyTony 888 pyMod Team Colleague Featured Poster

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.