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

标签 javascript regex

我有一个逗号分隔的单词列表,例如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}`);
    });
}

使用正则表达式可以吗?

最佳答案

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

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;
}

希望它能回答您的问题。

关于javascript - 正则表达式查找单词的最佳匹配子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58760600/

相关文章:

javascript - 使用正则表达式删除没有内容或只有空白的 div

javascript - 媒体查询断点上的 CSS 重置值(调整窗口大小或方向更改)

javascript - 如何使用 adobe dtm 更改页面名称?

正在删除 javascript 调用程序有什么选择?

Python正则表达式,如何匹配出现n次的字符串

java - IP 和字符串的正则表达式

javascript - 正则表达式在 Javascript 中转换 URL

javascript - 在 Javascript 中验证 Java 包名称的正则表达式

Python 正则表达式 交替运算符后没有组

javascript - 带有 javascript 的子字符串文本,包括 html 标签