诀窍是编写一个递归函数并将字符逐个匹配,直到找到'
*
'. 一次'
*
'遇到了什么都是公平的游戏,所以你可以返回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工具添加功能。例如,尝试添加'
?
'.