简体   繁体   English

在Ruby中的字符串中查找多个模式

[英]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. 我遍历了spamWord字符串数组,但是我想知道是否有更简单的方法来做到这一点。

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: 您还可以使用Regexp.union为您自动生成此regexp:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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