繁体   English   中英

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

[英]Check whether a string contains one of multiple substrings

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

例如

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/]

返回找到的第一个结果

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

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

如果部分搜索:

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

使用or代替||

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM