我有一个逗号分隔的单词列表,例如cooler、bestwishes、congrat。我想使用正则表达式来查找此列表中的最佳匹配单词。例如,Congratulations 或 Congrats 与上面列表中的 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/