1

我想用精确的字符串匹配两个数组之间的选项。

options = ["arish1", "arish2", "ARISH3", "arish 2", "arish"]
choices = ["Arish"]
final_choice = options.grep(Regexp.new(choices.join('|'), Regexp::IGNORECASE))
p final_choice

Output:
 ["arish1", "arish2", "ARISH3", "arish 2", "arish"]

but it should be only match "arish"
4

1 回答 1

1

你需要使用

final_choice = options.grep(/\A(?:#{Regexp.union(choices).source})\z/i)

请参阅Ruby 在线演示

笔记:

  • 正则表达式文字符号比构造函数符号更整洁
  • 您仍然可以在正则表达式文字中使用变量
  • Regexp.union方法在choices使用“或”正则表达式运算符时加入备选方案,并根据需要自动|转义项目
  • \Aanchor 匹配stirng 的开始并\z匹配stirng 的结束。
  • 非捕获组(?:...)用于确保将锚分别应用于每个备选方案choices
  • .source用于从正则表达式中获取模式部分。
于 2021-10-08T10:37:49.290 回答