如何扫描多个字符串的文本?

时间:2021-01-10 07:12:18

I'm scanning through a product name to check if a specific string exists in it. Right now it works for a single string, but how can I can scan for multiple strings? e.g. i'd like to scan for both apple and microsoft

我正在扫描一个产品名称,以检查其中是否存在一个特定的字符串。现在它只适用于一个字符串,但是我怎么才能扫描多个字符串呢?我想扫描苹果和微软

product.name.downcase.scan(/apple/)

If the string is detected i get ["apple"] if not then it returns nil [ ]

如果字符串被检测到,我得到["apple"]如果不是,那么它返回nil []

2 个解决方案

#1


5  

You can use regex alternation:

您可以使用regex交替:

product.name.downcase.scan(/apple|microsoft/)

If all you need to know is whether the string contains any of the specified strings, you should better use single match =~ instead of scan.

如果您需要知道的是字符串是否包含指定的字符串,那么您应该更好地使用单个match =~而不是扫描。

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

#2


2  

You could also skip regular expressions altogether:

你也可以跳过正则表达式:

['apple', 'pear', 'orange'].any?{|s| product.name.downcase.match(s)}

or

['apple', 'pear', 'orange'].any?{|s| product.name.downcase[s]}

#1


5  

You can use regex alternation:

您可以使用regex交替:

product.name.downcase.scan(/apple|microsoft/)

If all you need to know is whether the string contains any of the specified strings, you should better use single match =~ instead of scan.

如果您需要知道的是字符串是否包含指定的字符串,那么您应该更好地使用单个match =~而不是扫描。

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

#2


2  

You could also skip regular expressions altogether:

你也可以跳过正则表达式:

['apple', 'pear', 'orange'].any?{|s| product.name.downcase.match(s)}

or

['apple', 'pear', 'orange'].any?{|s| product.name.downcase[s]}