[英]ruby if string includes strict characters
我有一個數組:
array = ["abhor", "rage", "mad"]
並且我想檢查字符串是否在該數組中包含任何單詞-但僅包含該單詞(而不是子字符串)。
string = 'I made a cake.'
count = 0
array.each do |word|
if string.include? word
count += 1
end
end
然而,上面並增加count
,因為它撿了1 word
mad
,從made
在我的字符串。 我怎么能只搜索生氣,確保made
不被計數?
數組交集運算符 &
在這里很有用。
這是兩個選項,具體取決於您如何定義“單詞”:
1)如果一個單詞是任何非空白字符序列,則可以執行以下操作:
array & string.split
在您的示例中,這將導致數組和字符串中的單詞的交集為空。
2)如果單詞是包含_的任何字母數字字符序列,則可以執行以下操作:
array & string.scan(/\w+/)
例如,如果array = ["abhor", "rage", "mad", "cake"]
則上面的#1將為空(因為您有cake.
字符串中帶有句點),但將返回['cake']
對於方法2。
我會這樣做:
array = ["abhor", "rage", "mad"]
string = 'I made a cake.'
string.split.count{|word| array.include?(word)}
執行簡單拆分的問題是它不會考慮標點符號。 您需要的是一個正則表達式,它有點復雜。
array.each do |word|
count += 1 if string.match(/\W#{word}\W/)
end
嘗試先拆分單詞。
words = string.split
count = 0
words.each do |word|
count += 1 if array.include? word
end
如果您願意沿着正則表達式走,\\ b表示單詞邊界。 此示例(包括您句子中的所有單詞和一些片段)正確返回4。
array = ["abhor", "rage", "mad", "I", "made", "a", "cake", "cak"]
string = 'I made a cake.'
count = 0
array.each do |word|
if string =~ /\b#{word}\b/
count += 1
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.