使用Regexp::IGNORECASE匹配数组精确字符串出现多余结果如何解决
问题原因
- 你当前使用的正则没有添加首尾匹配锚点,只要字符串任意位置包含
Arish(不区分大小写)就会命中,因此所有带arish字样的元素都被匹配到了。
调整方案
方案1:修改正则增加锚定(适配多choice场景)
给每个匹配项增加正则行首(^)、行尾($)锚定,同时对匹配项做正则转义避免特殊字符引发匹配异常:
options = ["arish1", "arish2", "ARISH3", "arish 2", "arish"] choices = ["Arish"] # 每个选项包裹锚点并转义特殊字符 regex_pattern = choices.map { |item| "^#{Regexp.escape(item)}$" }.join('|') final_choice = options.grep(Regexp.new(regex_pattern, Regexp::IGNORECASE)) p final_choice # 输出:["arish"]
方案2:使用集合比对(性能更优,无正则风险)
如果不需要用到正则的复杂匹配能力,直接把两边统一大小写后做集合匹配更稳妥:
options = ["arish1", "arish2", "ARISH3", "arish 2", "arish"] choices = ["Arish"] # 提前把匹配项统一转小写存入集合 target_set = choices.map(&:downcase).to_set final_choice = options.select { |item| target_set.include?(item.downcase) } p final_choice # 输出:["arish"]
内容的提问来源于stack exchange,提问作者Arish Khan
相关产品推荐
相关产品推荐

