簡體   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