Welcome to MSDN Blogs Sign in | Join | Help

Armchair Programming: writing a wildcard function (glob)

Programming is a bit like music - you can develop your skills while you're away from the keyboard. All you have to do is think! Recently I was wondering (in the shower, actually) how briefly I could write a wildcard function. So just as an exercise, I had a go... here's my attempt.

The aim isn't to implement grep or perl style globbing, but just a simple wildcard match on * and ? (something like SQL Server wildcards):

    *   means match zero or more characters
    ?   means match any one character

Because this is an exercise in brevity, not performance, my version is recursive. Can you write a shorter version in C++?


bool WildMatch (const char *patt, const char *str)
{
  while (*patt)
  {
    if (*patt == '*')
    {
      patt++;
      while (*str)
        if (WildMatch(patt, str))
          return true;
        else
          str++;
    }
    else if ((*str) && ((*patt == '?') || (*patt == *str)))
    {
      patt++;
      str++;
    }
    else
      return false;
  }
  return (!*patt) && (!*str);
}

This posting is provided "AS IS" with no warranties, and confers no rights. Use of any included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm

 

Published Wednesday, January 18, 2006 8:59 AM by andrewdelin

Comments

Tuesday, January 17, 2006 7:28 PM by Wesner Moise

# .NET Undocumented

bool WildMatch(const char *patt, const char *str)
{
while(1)
{
if (*patt == '*')
return WildMatch(patt+1, str) || *str != 0 && WildMatch(patt, str+1);
if (*patt == 0 || *str == 0)
return *patt == *str;
if (*patt++ != *str++ && patt[-1] != '?')
return false;
}
}
Tuesday, January 17, 2006 7:36 PM by Wesner Moise

# re: Armchair Programming: writing a wildcard function (glob)

Recursive version:

bool WildMatch(const char *patt, const char *str)
{
if (*patt == '*')
return WildMatch(patt+1, str) || *str != 0 && WildMatch(patt, str+1);
if (*patt == 0 || *str == 0)
return *patt == *str;
return (*patt == *str || *patt == '?') && WildMatch(patt+1, str+1);
}
New Comments to this post are disabled
 
Page view tracker