简体   繁体   中英

Check whether a string contains one of multiple substrings

I've got a long string-variable and want to find out whether it contains one of two substrings.

eg

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:

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)

You can do a regex match:

haystack.match? /needle1|needle2/

Or if your needles are in an array:

haystack.match? Regexp.union(needles)

(For Ruby < 2.4, use .match without question mark.)

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

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

For an array of substrings to search for I'd recommend

needles = ["whatever", "pretty"]

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

To check if contains at least one of two substrings:

haystack[/whatever|pretty/]

Returns first result found

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') }

Use or instead of ||

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

or has lower presedence than || , or is "less sticky" if you will :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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