簡體   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