含有通配符*的字符匹配(C语言)
含有通配符的字符匹配,采用贪心算法
//1 -> true //0 -> false int IsMatch(const char* reg, const char *str) { int r_len = (int)strlen(reg); int r_p = 0; int r_p_last = -1; int s_len = (int)strlen(str); int s_p = 0; int s_p_last = -1; while (s_p < s_len) { if (r_p < r_len && (*(str + s_p) == *(reg + r_p))) { r_p++; s_p++; } else if (r_p < r_len && (*(reg + r_p) == '*')) { r_p_last = r_p; r_p++; s_p_last = s_p; } else if (r_p_last > -1) { r_p = r_p_last + 1; s_p_last++; s_p = s_p_last; } else { return 0;//false } } while (r_p < r_len && (*(reg + r_p) == '*')) { r_p++; } if (r_p == r_len) { return 1;//true } return 0;//false }
如果要匹配?的话,添加
*(reg + r_p) =='?'
就行了
if (r_p < r_len && (*(str + s_p) == *(reg + r_p))) {
if (r_p < r_len && (*(str + s_p) == *(reg + r_p)||*(reg + r_p) =='?')) {
注:之前匹配?的地方没写对,经过评论区的读者提醒,已经改正