检查字符串是否包含多个子字符串之一

时间:2014-05-08 00:33:07

标签: ruby-on-rails ruby string ruby-2.1

我有一个很长的字符串变量,想知道它是否包含两个子字符串中的一个。

e.g。

haystack = 'this one is pretty long'
needle1 = 'whatever'
needle2 = 'pretty'

现在我需要这样一个不能在Ruby中工作的分离:

if haystack.include? needle1 || haystack.include? needle2
    puts "needle found within haystack"
end

7 个答案:

答案 0 :(得分:68)

[needle1, needle2].any? { |needle| haystack.include? needle }

答案 1 :(得分:42)

在表达式中尝试parens:

 haystack.include?(needle1) || haystack.include?(needle2)

答案 2 :(得分:9)

(haystack.split & [needle1, needle2]).any?

使用逗号作为分隔符:split(',')

答案 3 :(得分:9)

如果使用Ruby 2.4,您可以使用|(或)来执行正则表达式匹配:

if haystack.match? /whatever|pretty|something/
  …
end

或者如果您的字符串在数组中:

if haystack.match? Regex.union(strings)
  …
end

(对于Ruby< 2.4,请使用不带问号的.match。)

答案 4 :(得分:5)

对于要搜索的子字符串数组,我建议

needles = ["whatever", "pretty"]

if haystack.match(Regexp.union(needles))
  ...
end

答案 5 :(得分:3)

检查是否包含两个子串中的至少一个:

haystack[/whatever|pretty/]

返回找到的第一个结果

答案 6 :(得分:0)

我试图找到一种简单的方法来搜索数组中的多个子串,最后以下面的方式回答问题。我已经添加了答案,因为我知道很多极客都会考虑其他答案,而不仅仅是被接受的答案。

haystack.select { |str| str.include?('wat') || str.include?('pre') }

如果部分搜索:

multipart/form-data
相关问题