Click here to Skip to main content
11,935,349 members (57,719 online)
Click here to Skip to main content
Add your own
alternative version


13 bookmarked

String Wildcard Matching (* and ?)

, 22 Jul 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple function to perform wildcard ( * ? ) string matching


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.


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;

            case Any:
                match = true;

            case AnyRepeat:
                match = true;

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

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


  • 22nd July, 2007: Initial post


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


About the Author

M Shahid Shafiq
Pakistan Pakistan
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralThanks Pin
BugMeNot ACCOUNT16-Jul-09 7:02
memberBugMeNot ACCOUNT16-Jul-09 7:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 22 Jul 2007
Article Copyright 2007 by M Shahid Shafiq
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid