通配符是 shell 命令中的重要功能,
? 表示匹配任意 1 個字符,
*表示匹配 0 個或多個字符。
請使用你熟悉的編程語言實現一個字符串匹配函數,
支持 ? 和 * 通配符。如 “a?cd*d” 匹配 “abcdaccd”
1 #coding:utf8
2 '''
3 通配符是 shell 命令中的重要功能, 4 ? 表示匹配任意 1 個字符, 5 *表示匹配 0 個或多個字符。 6 請使用你熟悉的編程語言實現一個字符串匹配函數, 7 支持 ? 和 * 通配符。如 “a?cd*d” 匹配 “abcdaccd” 8 '''
9
10 def solution( re_str,test_str ): 11 # 如果兩個字符串相等 就返回True
12 if re_str == test_str : 13 return True 14 # 標記第一個字母
15 r = re_str[0] if re_str != '' else ''
16 t = test_str[0] if test_str !='' else ''
17 # r 不是? 也 不是* 的情況
18 if r != '?' and r != '*' : 19 if r != t : # 如果不想相等就返回False
20 return False 21 else : # 相等 就 刪掉第一個單詞 遞歸
22 re_str,test_str = re_str[1:],test_str[1:] 23 return solution( re_str,test_str ) 24 # 如果r是? 相當於匹配一個字符 都刪掉一個字符 然后 遞歸
25 if r == '?' : 26 re_str, test_str = re_str[1:], test_str[1:] 27 return solution(re_str, test_str) 28 # 如果r是* re 是n個* 則返回True
29 if r == '*' and re_str.strip('*') == '' : 30 return True 31 # 否則 就是包含* ,*匹配0個字符或多個字符,所以我們返回 遞歸 0個匹配 與 1個匹配 的邏輯或
32 return solution(re_str[1:], test_str) or solution(re_str, test_str[1:]) 33
34
35
36 if __name__ == '__main__': 37 re_str = "a?*cd*d*"
38 test = "abcdaccd"
39 res = solution( re_str,test ) 40 print(res)