Game Development Community

dev|Pro Game Development Curriculum

Wildcard string matching

by Rick Overman · 12/14/2000 (10:54 pm) · 1 comments

A quick and dirty recursive wildcard string matcher.

This is a fun little snipit of code I found a long time ago. I wish I could remember where so I could give the proper credit.

The function below compares the given 'pattern' and 'string' and returns TRUE if they match,

otherwise FALSE. The pattern may consist of any alphanumeric character but the '?' and '*' are treated specially.

? Matches any single character.
* Matches any length string of characters (including none).

Here are a few examples and the return results.

match("*.txt", "foobar.txt"); => TRUE
match("*.txt", "foobat.doc"); => FALSE

match("?texture.png", "2texture.png"); => TRUE
match("?texture.png", "3texture.png"); => TRUE
match("?texture.png", "10texture.png"); => FALSE

match("?tree_*.png", "5tree_fir.png"); => TRUE
match("?tree_*.png", "6tree_pine.png"); => TRUE

bool match(const char *pattern, const char *string)
{
   switch (*pattern)
   {
      case '[[6287898370ea1]]':   return !*string;
      case '*':    return match(pattern+1, string) || 
                          *string && match(pattern, string+1);
      case '?':    return *string && match(pattern+1, string+1);
      default :    return (*pattern == *string) && 
                          match(pattern+1, string+1);
   }
}

#1
04/23/2002 (12:16 pm)
Clever! For some reason I always have a hard time coming up with recursive functions like this. Mine likely would have been another 10 lines or more to implement. :\