简体   繁体   中英

Finding multiple patterns in a string in Ruby

I am trying to find strings in an array that match multiple regular expression patterns. I figured out how to do this for one pattern as below:

spamWords = Regexp.new("Delighted")

spamCount1 = 0
spamArray.each do |word|
  if word =~ spamWords
    spamCount1 +=1
  end
end
p spamCount1

I iterated over an array of spamWord strings, but I was wondering if there is a simpler way of doing this.

You can union multiple patterns into one regular expression, then perform the search exactly like you did below:

spamWords = Regexp.new("Delighted|Saddened")

You can also use Regexp.union to auto-generate this regexp for you:

spamWords = Regexp.union("Delighted", "Saddened")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM