如何利用通配符模式匹配函数遍历字符串列表查找匹配项
通配符匹配函数的列表遍历实现方案
你现有的isMatch函数只能处理单个字符串与单个通配符模式的匹配,直接传入列表会因为参数类型不匹配(函数会把列表当作单个文本/模式,尝试逐个元素当作字符对比)而返回No。要实现列表级别的匹配,只需要添加遍历逻辑,逐个调用原函数即可。
原通配符匹配函数
def isMatch(text, pattern): n = len(text) m = len(pattern) i = 0 j = 0 startIndex = -1 match = 0 while i < n: if j < m and (pattern[j] == '?' or pattern[j] == text[i]): i += 1 j += 1 elif j < m and pattern[j] == '*': startIndex = j match = i j += 1 elif startIndex != -1: j = startIndex + 1 match += 1 i = match else: return False while j < m and pattern[j] == '*': j += 1 return j == m
方案1:对应位置的字符串与模式匹配
如果你的需求是字符串列表与模式列表按索引一一对应匹配(比如s[0]对应p[0],s[1]对应p[1]),可以写一个遍历函数:
def match_corresponding_items(text_list, pattern_list): # 可选:检查两个列表长度是否一致 if len(text_list) != len(pattern_list): print("字符串列表与模式列表长度不匹配") return [] results = [] for text, pattern in zip(text_list, pattern_list): is_matched = isMatch(text, pattern) status = "Yes" if is_matched else "No" print(f"字符串「{text}」与模式「{pattern}」匹配结果:{status}") results.append((text, pattern, is_matched)) return results # 测试示例 s = ['GUC 40 410','HUC 40 410','XUC 40 410'] p = ['GUC 40 4**','HUC 40 4**','XUC 40 4**'] match_corresponding_items(s, p)
运行后会输出每一组的匹配结果,你的示例中三组都会返回Yes,因为4**中的*可以匹配任意字符(包括10)。
方案2:多对多匹配(找出所有匹配组合)
如果需要字符串列表中的每个元素匹配模式列表中的任意模式,或者找出所有匹配的字符串-模式对,可以用如下逻辑:
def find_all_matching_pairs(text_list, pattern_list): matching_pairs = [] for text in text_list: matched_patterns = [] for pattern in pattern_list: if isMatch(text, pattern): matched_patterns.append(pattern) if matched_patterns: matching_pairs.append({ "字符串": text, "匹配模式": matched_patterns }) print(f"字符串「{text}」匹配以下模式:{', '.join(matched_patterns)}") else: print(f"字符串「{text}」未匹配任何模式") return matching_pairs # 测试示例 find_all_matching_pairs(s, p)
为什么直接传列表会失败?
原函数的参数text和pattern预期是单个字符串,当传入列表时:
- 函数会把列表的长度当作文本/模式的长度
- 尝试逐个对比列表的元素(字符串)和模式的元素(字符串),而不是字符串的单个字符
- 这种类型不匹配的对比必然返回
False,所以输出No
内容的提问来源于stack exchange,提问作者Kerry Harp
相关产品推荐
相关产品推荐

