Check whether a string contains one of multiple substrings

后端 未结 7 1292
挽巷
挽巷 2020-12-23 19:32

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          


        
相关标签:
7条回答
  • 2020-12-23 20:03

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

    needles = ["whatever", "pretty"]
    
    if haystack.match(Regexp.union(needles))
      ...
    end
    
    0 讨论(0)
  • 2020-12-23 20:03

    To check if contains at least one of two substrings:

    haystack[/whatever|pretty/]
    

    Returns first result found

    0 讨论(0)
  • 2020-12-23 20:11
    (haystack.split & [needle1, needle2]).any?
    

    To use comma as separator: split(',')

    0 讨论(0)
  • 2020-12-23 20:20
    [needle1, needle2].any? { |needle| haystack.include? needle }
    
    0 讨论(0)
  • 2020-12-23 20:21

    In Ruby >= 2.4 you can do a regex match using | (or):

    haystack.match? /whatever|pretty|something/
    

    Or if your strings are in an array:

    haystack.match? Regexp.union(strings)
    

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

    0 讨论(0)
  • 2020-12-23 20:26

    Try parens in the expression:

     haystack.include?(needle1) || haystack.include?(needle2)
    
    0 讨论(0)
提交回复
热议问题