繁体   English   中英

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

[英]Check if string matches multiple substrings/regexes

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

有没有一种方法可以使用一个Regexp.union或一个regex,而无需=~ regex1 && =~ regex2 && =~ regex3 && =~ regex4等?

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

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

我建议以下内容:

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

我从未使用过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
}

暂无
暂无

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

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