通配符匹配字符串

时间:2018-01-29 09:09:30

标签: c string algorithm wildcard

我正在尝试编写一个函数bool match(char pattern[], char expresssion[]) 检查模式是否与表达式匹配。如果模式中出现*,则它可以与任何字符串匹配 - 空字符串也是如此。这就是我的问题所在。

我正在努力迎合这位明星。我的第一个想法是检查明星之后出现的下一个字符,看它是否出现在表达式中。如果它出现在第n个位置,我在模式中移动一个字符并开始从第n个位置进一步检查表达式。但是,我是否应该从左侧或右侧检查我的表达并不总是显而易见的。例如 - 如果从左侧检查,则此测试将失败:

match("a*b", "ababab")

因为只有第一个" b"会"吞噬"由明星。相反,如果我从右边检查,那么这个测试就会失败:

match("a*b*b*", "abbbbbbbba")

你能否告诉我如何处理这位明星?

1 个答案:

答案 0 :(得分:2)

诀窍是编写递归函数并匹配类似的字符,直到找到“*”。一旦遇到'*',那么任何事情都是合理的游戏,所以你可以返回true。

bool match(char const *pattern, char const *file) {
    for (; *pattern != '\0'; ++pattern) {
        switch (*pattern) {
        case '*': {
            //if pattern terminates after * then file can be anything, thus
            //terminate and return true.
            if (pattern[1] == '\0')
                return true;
            //pattern doesn't terminate so cut off '*' from pattern,
            //increment file and repeat.
            size_t max = strlen(file);
            for (size_t i = 0; i < max; i++)
                if (match(pattern + 1, file + i))
                    return true;
            return false;
        }
        default:
            //if pattern doesn't specify a '?' or a '*', it must be a regular
            //character and so, must require a like for like match with file.
            if (*file != *pattern)
                return false;
            ++file;
        }
    }
    //we have iterated through the whole of pattern and so file must end too
    //if we are to match.
    return *file == '\0';
}

然后,您可以在switch语句中添加额外的分支,并为glob工具添加功能。例如,尝试添加“?”的逻辑。