rhanly
rhanly

Reputation: 91

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.

Upvotes: 0

Views: 275

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

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")

Upvotes: 2

Related Questions