如何扫描多个字符串的文本?
问题描述:
我正在扫描产品名称以检查其中是否存在特定的字符串。现在它适用于单个字符串,但我怎样才能扫描多个字符串?例如我想扫描两个苹果和微软如何扫描多个字符串的文本?
product.name.downcase.scan(/apple/)
如果检测到字符串,我得到[“苹果”] 如果没有的话则返回nil []
答
您可以使用regex alternation:
product.name.downcase.scan(/apple|microsoft/)
如果你需要知道的是字符串是否包含任何指定的字符串,你应该更好地使用单个匹配=~,而不是scan
。
str = 'microsoft, apple and microsoft once again'
res = str.scan /apple|microsoft/ # => res = ["microsoft", "apple", "microsoft"]
# do smth with res
# or
if str =~ /apple|microsoft/
# do smth
end
答
你也可以完全跳过的正则表达式:
['apple', 'pear', 'orange'].any?{|s| product.name.downcase.match(s)}
或
['apple', 'pear', 'orange'].any?{|s| product.name.downcase[s]}
真棒,我很感激! – ahuang7 2012-02-29 08:48:40