字符串通配符匹配算法

/**
 * match char
 *
 * @param c1 first character
 * @param c2 second character
 * @param ignoreCase ignore case
 * @return true means match, otherwise not match
 */
bool MatchChar(char c1, char c2, bool ignoreCase)
{
    return c1 == c2 || (ignoreCase && tolower(c1) == tolower(c2));
}

/**
 * match file name
 * <p>
 *    support special character
 *    * : any character
 * </p>
 *
 * @param filename file name
 * @param pattern pattern string
 * @param ignoreCase ignore case
 * @return
 */
bool WildCharMatch(IN const char* src, IN const char* pattern, IN const bool ignoreCase)
{
    if (!src || !pattern)
    {
        return false;
    }

    bool result;
    while (*src)
    {
        if (*pattern == '*')
        {
            // If pattern current character '*'
            // If there are multiple '*', skip over
            while ((*pattern == '*') || (*pattern == '?'))
            {
                pattern++;
            }

            // If there is no character after '*', then match correctly.
            if (!*pattern)
            {
                return true;
            }

            while (*src)
            {
                // find a character in src that is identical to the character in pattern
                if (MatchChar(*src, *pattern, ignoreCase))
                {
                    // If found, match the remaining string.
                    result = WildCharMatch(src, pattern, ignoreCase);
                    if (result)
                    {
                        return true;
                    }
                }
                src++;
            }
            return false;
        }
        else
        {
            // If the current character in pattern is not '*'
            // Match current characters
            if (MatchChar(*src, *pattern, ignoreCase) || ('?' == *pattern))
            {
                // SRC, pattern advance one, continue to match.
                return WildCharMatch(++src, ++pattern, ignoreCase);
            }
            
            return false;
        }
    }

    // If src is over, see if pattern ends.
    if (*pattern)
    {
        // pattern didn't end
        // If pattern has the last character and is '*'
        if (*pattern == '*' && *(pattern + 1) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    return true;
}
原创文章 10 获赞 0 访问量 362

猜你喜欢

转载自blog.csdn.net/weixin_43803007/article/details/84563039