【发布时间】:2020-03-04 17:37:48
【问题描述】:
我有一个逗号分隔的单词列表,例如 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}`);
});
}
这可以使用正则表达式吗?
【问题讨论】:
-
你能给出一个匹配的单词列表吗?
-
单词列表是:cool,bestwishes,congrat,greatjob,welldone,kudos,thumbsup,keeprocking。正则表达式将有一个与上述匹配的单词。所以让我们说如果正则表达式包含keeprockingbuddy,它应该匹配keeprocking
-
有什么问题,你实施了什么?
-
正则表达式 /[^,]*congratulation[^,]*/gi 没有返回 congrat
-
正则表达式适用于精确比较,而不适用于近似比较。使用模糊匹配器,就像这个潜在的重复:Javascript fuzzy search that makes sense,
标签: javascript regex