如何找出数组中与带问号占位符的给定字符串匹配的所有值?
实现带问号的单词匹配功能
需求说明
给定一个字符串数组,当输入一个用问号替代部分字符的字符串时,返回数组中所有符合匹配规则的单词。示例如下:
待匹配数组:
possibleWords = ["Animal", "Basket", "Bridge", "Guitar", "Needle", "Office", "Orange"]
输入匹配模式"O????e"时,应返回结果["Office", "Orange"]
解决方案
通过遍历数组单词,逐个字符对比模式与单词的对应位置即可实现匹配逻辑,具体代码如下:
基础实现代码
possibleWords = ["Animal", "Basket", "Bridge", "Guitar", "Needle", "Office", "Orange"] def find_matching_words(pattern, word_list): matches = [] pattern_length = len(pattern) # 先过滤长度不匹配的单词,减少不必要的对比 for word in word_list: if len(word) != pattern_length: continue # 逐个字符校验匹配规则 is_match = True for p_char, w_char in zip(pattern, word): if p_char != '?' and p_char != w_char: is_match = False break if is_match: matches.append(word) return matches # 测试示例 print(find_matching_words("O????e", possibleWords)) # 输出: ['Office', 'Orange']
代码逻辑说明
- 第一步过滤掉长度与模式不一致的单词,这类单词必然不匹配,直接跳过
- 对长度匹配的单词,逐个字符对比:若模式字符不是问号,则必须与单词对应字符完全相同
- 所有字符都符合规则的单词,加入结果列表返回
可选扩展:忽略大小写匹配
如果需要支持大小写不敏感的匹配,可以在对比前统一转换为小写(或大写):
def find_matching_words_case_insensitive(pattern, word_list): matches = [] pattern_length = len(pattern) pattern_lower = pattern.lower() for word in word_list: if len(word) != pattern_length: continue word_lower = word.lower() is_match = True for p_char, w_char in zip(pattern_lower, word_lower): if p_char != '?' and p_char != w_char: is_match = False break if is_match: matches.append(word) return matches
内容的提问来源于stack exchange,提问作者BlackNinja745 Studios
相关产品推荐
相关产品推荐

