检查字符串是否匹配多个子字符串/正则表达式

时间:2015-03-16 06:26:46

标签: ruby regex

我有一系列段落和一系列关键字。我想迭代段落数组并返回包含所有关键字的元素的true。关键字可以按任意顺序排列,但必须在同一段落中找到所有关键字才能使其成为true,而不仅仅是其中的一部分。

有没有办法可以使用一个Regexp.union或一个正则表达式执行此操作,而不使用=~ regex1 && =~ regex2 && =~ regex3 && =~ regex4等?

3 个答案:

答案 0 :(得分:0)

如果模式数组只包含关键字而没有模式:

str = "foo went to bar with abc and xyz"

pats = ["abc","xyz","foo","bar"]
pats.all? { |e| str.include?(e) }
# => true

pats = ["abc","xyz","foo","bar", "no"]
pats.all? { |e| str.include?(e) }
# => false

如果模式数组包含模式:

pats = [/abc/, /xyz$/, /^foo/, /bar/]
pats.all? { |e| str =~ e }
# => true

pats = [/abc/, /xyz$/, /^foo/, /bar/, /no/]
pats.all? { |e| str =~ e }
# => false

答案 1 :(得分:0)

我建议如下:

str = "I have an array of paragraphs and an array of keywords. I want to iterate over the paragraphs array and return true for elements that include all of my keywords. The keywords can be in any order, but all of them must be found in the same paragraph in order for it to be true, not just some of them."

编辑:我最初误解了这个问题。您可以为每个段落执行以下操作:

words = %w(have iterate true) 
(words - str.scan(/\w+/)).empty?
  #=> true

words = %w(have iterate cat)
(words - str.scan(/\w+/)).empty?
  #=> false

当我最初阅读问题时,我认为数组中的单词必须以相同的顺序出现在每个段落。为了记录,我的解决方案遵循该附加要求。

words = %w(have iterate true)   
r = /\b#{words.join('\b.*?\b')}\b/
   #=> /\bhave\b.*?\biterate\b.*?\btrue\b/
str =~ r #=> 2 (a match)

words = %w(true have iterate)
r = /\b#{words.join('\b.*?\b')}\b/
str =~ r #=> nil

words = %w(have iterate true false)   
r = /\b#{words.join('\b.*?\b')}\b/
str =~ r #=> nil

答案 2 :(得分:-1)

我从未使用过Ruby,但我可以在这里给你使用逻辑。希望它有所帮助

array_words
array_paragraphs
number_words = array_words
count =0

foreach para (array_paragraph)
{
    foreach word (array_word)
    {
        if (para =~ m/word/gi)
        {
            count++
        }
    }
    if (count == number_words)
    {
        print all words present in the paragraph
    }
    count = 0
}