53

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

例如

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

现在我需要一个像这样的析取,它在 Ruby 中不起作用:

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

8 回答 8

95
[needle1, needle2].any? { |needle| haystack.include? needle }
于 2015-03-15T14:21:09.857 回答
63

在表达式中尝试括号:

 haystack.include?(needle1) || haystack.include?(needle2)
于 2014-05-08T00:39:25.500 回答
21

您可以进行正则表达式匹配:

haystack.match? /needle1|needle2/

或者,如果您的针在阵列中:

haystack.match? Regexp.union(needles)

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

于 2017-02-21T22:58:34.423 回答
10
(haystack.split & [needle1, needle2]).any?

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

于 2015-02-27T14:07:14.157 回答
9

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

needles = ["whatever", "pretty"]

if haystack.match?(Regexp.union(needles))
  ...
end
于 2017-04-07T12:58:33.120 回答
5

检查是否至少包含两个子字符串之一:

haystack[/whatever|pretty/]

返回找到的第一个结果

于 2018-01-25T07:58:23.230 回答
1

使用or代替||

if haystack.include? needle1 or haystack.include? needle2

or具有比 更低的存在性||,或者如果你愿意的话是“不那么粘” :-)

于 2022-01-19T07:48:58.083 回答
0

我试图找到一种简单的方法来搜索数组中的多个子字符串,并最终在下面也回答了这个问题。我已经添加了答案,因为我知道许多极客会考虑其他答案,而不仅仅是接受的答案。

haystack.select { |str| str.include?(needle1) || str.include?(needle2) }

如果部分搜索:

haystack.select { |str| str.include?('wat') || str.include?('pre') }
于 2017-06-02T07:38:58.310 回答