使用 Regex 字符串按组或其他方式查找 2 个或更多单词

Use Regex string to find 2 or more word by group or other means

正在寻找可以优化问题库搜索结果的正则表达式字符串。 例子: 问题:如何与朋友开始对话?

使用 -> 正则表达式字符串

题库-

  1. 开始与朋友对话
  2. 与我的朋友建立对话
  3. 开始与我的朋友对话
  4. 开始游戏
  5. 通过说“你好,人名”开始对话

回答- 1, 2, 3. - 是答案 4,5 - 不相关

目前,我正在使用 WordNet 获取名词和动词,然后通过查询找到结果。 是否可以搜索至少找到 2 个词的问题? 当前正则表达式:/(?=.*\bstart\b)(?=.*\bconversation\b)(?=.*\bfriend\b).*/gi Returns 仅当找到所有单词时。

使用简单的 indexOf 会更容易。我认为它也会更快。

const words = [...];
let matchedWord = 0;
for(let word of words){
  if(questionSentence.indexOf(word) > -1) matchedWord+=1
  if(matchedWord > 1) {
    return questionSentence;
  }
}

复杂性的产生是因为你需要知道一个词在过去是否匹配。我真的不会为此使用正则表达式。您甚至可以将它包装成这样的函数:

function matchWords(sentence, words, threshold){
    const lowercaseSentence = sentence.toLowerCase();
    let matchedWord = 0;
    for(let word of words){
      if(lowercaseSentence.indexOf(word.toLowerCase()) > -1) {
          matchedWord+=1
      }
      if(matchedWord >= threshold) {
        return true;
      }
    }
    return false;
}

花了一些时间,但我找到了一个答案。 用于从句子列表中搜索单词列表的正则表达式字符串: 请注意,需要 N 个阈值(这意味着生成的句子中应包含 N 个或更多单词。)

正则表达式字符串: //对于 N = 2 /(word1|word2|word3|)([ -z]*)?(word1|word2|word3)/gi

//对于 N = 3 /(word1|word2|word3|)([ -z]*)?(word1|word2|word3)([ -z]*)(word1|word2|word3)/gi