Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

String Wildcard Matching (* and ?)

1.70/5 (11 votes)
22 Jul 2007CPOL 1  
A simple function to perform wildcard ( * ? ) string matching

Introduction

I had a problem where I wanted to match a string against a pattern based on wild characters (* and ?). The function presented in this article is a simple one that does this matching. Here are some sample patterns:

  • sam*
  • sam*e
  • samp?e
  • s*p?e
  • etc.

Using the Code

The usage of the function is very simple. Just call the function with two arguments. The first one is the string to be compared with the pattern specified in the second argument. The function does not perform any error checking.

C++
//
//  

bool pattern_match(const char *str, const char *pattern) {
    enum State {
        Exact,      	// exact match
        Any,        	// ?
        AnyRepeat    	// *
    };

    const char *s = str;
    const char *p = pattern;
    const char *q = 0;
    int state = 0;

    bool match = true;
    while (match && *p) {
        if (*p == '*') {
            state = AnyRepeat;
            q = p+1;
        } else if (*p == '?') state = Any;
        else state = Exact;

        if (*s == 0) break;

        switch (state) {
            case Exact:
                match = *s == *p;
                s++;
                p++;
                break;

            case Any:
                match = true;
                s++;
                p++;
                break;

            case AnyRepeat:
                match = true;
                s++;

                if (*s == *q) p++;
                break;
        }
    }

    if (state == AnyRepeat) return (*s == *q);
    else if (state == Any) return (*s == *p);
    else return match && (*s == *p);
} 

History

  • 22nd July, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)