【问题标题】:Finding multiple patterns in a string in Ruby在 Ruby 中查找字符串中的多个模式
【发布时间】:2019-04-22 22:16:15
【问题描述】:

我正在尝试在数组中查找与多个正则表达式模式匹配的字符串。我想出了如何为以下一种模式执行此操作:

spamWords = Regexp.new("Delighted")

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

我遍历了一个 spamWord 字符串数组,但我想知道是否有更简单的方法。

【问题讨论】:

  • 如果您只想计算而不是获取匹配项,那么您应该这样做:smapArray.count(&spamWords.method(:=~))。

标签: arrays ruby regex


【解决方案1】:

您可以将多个模式合并到一个正则表达式中,然后像下面一样执行搜索:

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

您也可以使用Regexp.union 为您自动生成此正则表达式:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2022-01-07
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多