正则表达式查找单词的最佳匹配子集

Posted

技术标签:

【中文标题】正则表达式查找单词的最佳匹配子集【英文标题】:Regex to find the best matching subsetof a word 【发布时间】:2020-03-04 17:37:48 【问题描述】:

我有一个逗号分隔的单词列表,例如 cooler、bestwishes、congrat。我想使用正则表达式在此列表中查找最佳匹配词。例如,CongratulationsCongrats 与上述列表中的 congrat 匹配。

我已经尝试过下面的正则表达式,但它只有在正则表达式中的单词是子集时才有效。

const regex = /[^,]*congratulation[^,]*/g;
const str = `this,cart,open,best-wishes,congrat`;
let m;

while ((m = regex.exec(str)) !== null) 
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) 
        regex.lastIndex++;
    

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => 
        console.log(`Found match, group $groupIndex: $match`);
    );


这可以使用正则表达式吗?

【问题讨论】:

你能给出一个匹配的单词列表吗? 单词列表是:cool,bestwishes,congrat,greatjob,welldone,kudos,thumbsup,keeprocking。正则表达式将有一个与上述匹配的单词。所以让我们说如果正则表达式包含keeprockingbuddy,它应该匹配keeprocking 有什么问题,你实施了什么? 正则表达式 /[^,]*congratulation[^,]*/gi 没有返回 congrat 正则表达式适用于精确比较,而不适用于近似比较。使用模糊匹配器,就像这个潜在的重复:javascript fuzzy search that makes sense, 【参考方案1】:

您可以在目标单词中搜索单词列表,而不是在单词列表中搜索目标单词的子字符串。这将降低复杂性并使其更容易。

let words = ["cool","bestwishes","congrat","greatjob","welldone","kudos","thumbsup","keeprocking","rock","congrats"];
let word = "keeprockingbuddy";
let match = getMatchingWords(words,word);
console.log(match); // ["keeprocking", "rock"]
match = getMatchingWords(words,"Congratulations"); 
console.log(match); // ["congrat"]


function getMatchingWords(words,target)
  let ans = [];
  words.forEach((w)=>
    let found = target.match(new RegExp(w,"i"));
    if(found)
      ans.push(w);
    
  )
  ans = ans.length ? ans:"not found";
  return ans;

希望它能回答你的问题。

【讨论】:

以上是关于正则表达式查找单词的最佳匹配子集的主要内容,如果未能解决你的问题,请参考以下文章

正则表达式。匹配整个单词

如何使用正则表达式

❤️Linux三剑客与管道符正则表达式的使用❤️

正则表达式

在 Redshift 中使用正则表达式来获取匹配模式之前的单词

正则表达式