我有一组段落和一组关键字。我希望遍历段落数组,并为包含我所有关键字的元素返回true。关键字可以是任何顺序,但必须在同一段落中找到所有关键字,才能使其为true,而不仅仅是其中的一部分。
有没有一种方法可以在没有=~ regex1 && =~ regex2 && =~ regex3 && =~ regex4的情况下使用一个Regexp.union或一个正则表达式来完成这项工作?
发布于 2015-03-16 14:37:17
如果模式数组只包含关键字而不包含模式:
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发布于 2015-03-16 15:12:06
我的建议如下:
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发布于 2015-03-16 15:39:39
我从来没有使用过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
}https://stackoverflow.com/questions/29070760
复制相似问题