gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:35:27 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com