Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式来查找单词的最佳匹配子集_Javascript_Regex - Fatal编程技术网

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

Javascript 正则表达式来查找单词的最佳匹配子集,javascript,regex,Javascript,Regex,我有一张单子,上面写着“酷”、“祝福”、“祝贺”。我想使用正则表达式在这个列表中找到最匹配的单词。e、 g祝贺您或祝贺您匹配上表中的祝贺您 我试过下面的正则表达式,但它只在正则表达式中的单词是子集时有效 const regex = /[^,]*congratulation[^,]*/g; const str = `this,cart,open,best-wishes,congrat`; let m; while ((m = regex.exec(str)) !== null) { //

我有一张单子,上面写着“酷”、“祝福”、“祝贺”。我想使用正则表达式在这个列表中找到最匹配的单词。e、 g祝贺您祝贺您匹配上表中的祝贺您

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

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


这是否可能使用regex?

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

let words=[“酷”、“最美好的祝愿”、“恭喜”、“干得好”、“很好”、“很好”、“很好”、“拇指支撑”、“继续前进”、“摇滚”、“恭喜”];
让word=“keeprockingbuddy”;
让match=getMatchingWords(words,word);
console.log(匹配);//[“继续前进”,“摇滚乐”]
match=getMatchingWords(单词“恭喜”);
console.log(匹配);//[“Congat”]
函数getMatchingWords(单词,目标){
设ans=[];
words.forEach((w)=>{
let found=target.match(新的RegExp(w,“i”);
如果(找到){
反推力(w);
}
})
ans=ans.length?ans:“未找到”;
返回ans;

}
你能给出一个匹配的单词列表吗?单词列表是:酷、祝福、祝贺、很棒的工作、干得好、荣誉、拇指支撑、继续前进。正则表达式将有一个单词与上面的匹配。因此,假设正则表达式包含keeprockingbuddy,那么它应该与keeprockingWhat is problem,what your implementation匹配?正则表达式/[^,]*祝贺[^,]*/gi没有返回Congreatregex用于精确比较,而不是近似比较。使用模糊匹配器,如以下潜在重复:,