Ruby-on-rails 检查字符串是否包含多个子字符串之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23530762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether a string contains one of multiple substrings
提问by Hedge
I've got a long string-variable and want to find out whether it contains one of two substrings.
我有一个很长的字符串变量,想知道它是否包含两个子字符串之一。
e.g.
例如
haystack = 'this one is pretty long'
needle1 = 'whatever'
needle2 = 'pretty'
Now I'd need a disjunction like this which doesn't work in Ruby though:
现在我需要一个像这样的分离,但在 Ruby 中不起作用:
if haystack.include? needle1 || haystack.include? needle2
puts "needle found within haystack"
end
回答by seph
[needle1, needle2].any? { |needle| haystack.include? needle }
回答by danh
Try parens in the expression:
在表达式中尝试括号:
haystack.include?(needle1) || haystack.include?(needle2)
回答by emlai
If Ruby 2.4, you can do a regex match using |(or):
如果是 Ruby 2.4,您可以使用|(或)进行正则表达式匹配:
if haystack.match? /whatever|pretty|something/
…
end
Or if your strings are in an array:
或者,如果您的字符串在数组中:
if haystack.match? Regex.union(strings)
…
end
(For Ruby < 2.4, use .matchwithout question mark.)
(对于 Ruby < 2.4,.match不带问号使用。)
回答by rgtk
(haystack.split & [needle1, needle2]).any?
To use comma as separator: split(',')
使用逗号作为分隔符: split(',')
回答by Seph Cordovano
For an array of substrings to search for I'd recommend
对于要搜索的子字符串数组,我建议
needles = ["whatever", "pretty"]
if haystack.match(Regexp.union(needles))
...
end
回答by Kapitula Alexey
To check if contains at least one of two substrings:
检查是否至少包含两个子字符串之一:
haystack[/whatever|pretty/]
Returns first result found
返回找到的第一个结果
回答by Shiko
I was trying to find simple way to search multiple substrings in an array and end up with below which answers the question as well. I've added the answer as I know many geeks consider other answers and not the accepted one only.
我试图找到一种简单的方法来搜索数组中的多个子字符串,并最终得到下面的答案。我已经添加了答案,因为我知道许多极客会考虑其他答案,而不仅仅是接受的答案。
haystack.select { |str| str.include?(needle1) || str.include?(needle2) }
and if searching partially:
如果部分搜索:
haystack.select { |str| str.include?('wat') || str.include?('pre') }

