我有一个长字符串变量,想知道它是否包含两个子字符串之一。
例如
haystack = 'this one is pretty long'
needle1 = 'whatever'
needle2 = 'pretty'
现在我需要一个像这样的析取,它在 Ruby 中不起作用:
if haystack.include? needle1 || haystack.include? needle2
puts "needle found within haystack"
end
我有一个长字符串变量,想知道它是否包含两个子字符串之一。
例如
haystack = 'this one is pretty long'
needle1 = 'whatever'
needle2 = 'pretty'
现在我需要一个像这样的析取,它在 Ruby 中不起作用:
if haystack.include? needle1 || haystack.include? needle2
puts "needle found within haystack"
end
[needle1, needle2].any? { |needle| haystack.include? needle }
在表达式中尝试括号:
haystack.include?(needle1) || haystack.include?(needle2)
您可以进行正则表达式匹配:
haystack.match? /needle1|needle2/
或者,如果您的针在阵列中:
haystack.match? Regexp.union(needles)
(对于 Ruby < 2.4,使用.match
不带问号。)
(haystack.split & [needle1, needle2]).any?
使用逗号作为分隔符:split(',')
对于要搜索的子字符串数组,我建议
needles = ["whatever", "pretty"]
if haystack.match?(Regexp.union(needles))
...
end
检查是否至少包含两个子字符串之一:
haystack[/whatever|pretty/]
返回找到的第一个结果
使用or
代替||
if haystack.include? needle1 or haystack.include? needle2
or
具有比 更低的存在性||
,或者如果你愿意的话是“不那么粘” :-)
我试图找到一种简单的方法来搜索数组中的多个子字符串,并最终在下面也回答了这个问题。我已经添加了答案,因为我知道许多极客会考虑其他答案,而不仅仅是接受的答案。
haystack.select { |str| str.include?(needle1) || str.include?(needle2) }
如果部分搜索:
haystack.select { |str| str.include?('wat') || str.include?('pre') }