DOS-Like Wildcard Matching

June 01, 2014comments

Here is the tiniest recursive algorithm I could come up with to perform string matching with DOS-like wildcard support. Let me know if you find any simpler implementation.

bool wildcardMatch(const char* p, const char* s) {
    while (*p != '\0') {
        if (*p == '*') {
            if (wildcardMatch(p + 1, s)) {
                return true;
            }
        } else if (*p == '?' || tolower(*p) == tolower(*s)) {
            ++p;
        } else {
            return false;
        }
        ++s;
    }
    return (*s == '\0');
}

p is pattern to match (? matches any character, * matches any substring, any other letter is compared with disregard for case).
s is string to test

Source with unit-test.