0

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.

1
  • If you just want to count rather than get the matches, then you should do: smapArray.count(&spamWords.method(:=~)). Commented Nov 21, 2018 at 3:28

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.