a 中 * 匹配任意長度的 [a-z0-9] 字符* 不匹配 . (點號)int diff_str(const char *a, const char *b) {
const char *star = NULL; // 記錄模式串中 * 的位置
const char *b_at_star = NULL; // 記錄文本串對應 * 時的位置
while (*b) {
if (*a == *b || *a == '*') {
if (*a == '*') {
star = a++; // 記錄 * 位置,模式串前進
b_at_star = b; // 文本串當前位置
continue;
}
a++; b++; // 字符匹配,雙雙前進
} else if (star) {
// 失配但曾有 *:回溯,讓 * 多吞一個字符
a = star + 1; // 模式串回到 * 後
b = ++b_at_star; // 文本串前進一位
} else {
return 0; // 失配且無 * 可用
}
}
// 文本結束,模式串剩餘必須全為 *
while (*a == '*') a++;
return *a == '\0' ? 1 : 0;
}
*a == *b 直接比較字符,'.' != 'a' 等,自然滿足「* 不匹配 .」。* 優先嘗試匹配 0 字符,失敗時回溯多吞一個(++b_at_star)。b 掃描一次,b_at_star 只增不減,無指數回溯。diff_str("hello*world", "hello.world") // 0 (.* 不匹配 .)
diff_str("hello*world", "hellower9world") // 1
diff_str("*", "adfafdafd") // 1
diff_str("s*t*s", "sts") // 1 (* 匹配空串)
diff_str("s*t*s", "sat.s") // 0 (含 .)
diff_str("au*ex*.bat", "autoexec.bat") // 1
**:視為單個 *,代碼自動兼容* 結尾:while (*a == '*') a++ 正確處理diff_str("", "") == 1,diff_str("*", "") == 0(需 * 匹配至少 0 字符,按需求可調整)此算法為標準通配符匹配的高效實現,廣泛用於 Shell glob、Git ignore、文件系統過濾等場景。