【问题标题】:Ruby variable regular expression in Array SelectArray Select 中的 Ruby 变量正则表达式
【发布时间】:2019-04-28 15:41:41
【问题描述】:

我正在尝试使用array.select 从字符串数组中排除元素。我有这个方法:

def filter_out_other_bad_vals(array_of_strs, things_i_want)
  array_of_strs = array_of_strs.select { |line| /"#{things_i_want}"/.match(line) } 
end 

我想将字符串作为变量things_i_want 传递。但这不会返回任何匹配项:

array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
pattern = 'want_this'
array = filter_out_other_bad_vals(array, pattern)

这将返回一个空数组。但是如果我硬编码匹配表达式中的值,我会得到我想要的。

def filter_out_other_bad_vals(array_of_strs, things_i_want)
  array_of_strs = array_of_strs.select { |line| /want_this/.match(line) } 
end 

如何在正则表达式中添加变量?我究竟做错了什么?

我可以遍历数组,检查每个项目,然后将值保存在另一个数组中,但这不太像 ruby​​,是吗?

【问题讨论】:

  • 如果您想根据正则表达式进行过滤(给定的问题不清楚),那么您可以使用array.grep(/want_this/)pattern = /want_this/ 后跟array.grep(pattern) ... 获取匹配元素以外的内容,使用grep_v 而不是grep

标签: arrays ruby regex select


【解决方案1】:

您在正则表达式定义中包含引号:

 /"#{things_i_want}"/

删除它们,它应该可以工作:

/#{things_i_want}/

编辑: 顺便说一句,您不必使用正则表达式进行精确匹配,您可以使用相等检查 (==) 或 #include?,具体取决于您是否需要一个字符串等于您想要的内容或仅包含它:

> array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
> array.select{|line| line == 'want_this'}
# => ["want_this", "want_this", "want_this"]
> array.select{|line| line.include? 'want_this'}
# => ["want_this", "want_this", "want_this"]

【讨论】:

  • 何塞,请注意"do_not_want_this".match?(/want_this/) #=> true。如果此处需要false,请在此处添加锚点(/\Awant_this\z/,其中\A\z 是字符串的开头和结尾),或者更好,如本答案中所建议,只需line == 'want_this'
  • 谢谢,我不是要精确匹配。上下文是一些解析 DNS 区域传输查询的 ruby​​。它返回的 CNAMES 产生了不想要的结果……长篇大论。我想我会简化我的编码示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
相关资源
最近更新 更多