我有一个名字数组;
["Agent 1", "Agent 12", "Agent 2"]
我将收到一个字符串(可能包含也可能不包含数组中的某个单词),我需要对其进行搜索,如果找到匹配项,则返回数组值。
例如,我可能会收到字符串。
I spoke to Agent 1 the other day.
我使用以下算法来搜索任何匹配项。
for (var i in agent_names) {
var name = agent_names[i];
if (msg.toLowerCase().indexOf(name.toLowerCase()) !== -1) {
return agent_names[i];
}
}
return null;
这对于代理 1
效果很好。但是,如果同一条消息说;
I spoke to Agent 12 the other day.
该算法仍将匹配 Agent 1
,因为它是字符串的一部分。
本质上,我正在寻找最适合的搜索而不是首次适合。 indexOf
在此实例中不起作用。
我能想到的唯一方法是通过字母暴力破解并存储最长的匹配。但这似乎效率很低?
最佳答案
在匹配循环开始之前对单词数组进行排序:
agent_names = agent_names.sort(function(i,j){return i.length < j.length})
for (var i in agent_names) {
var name = agent_names[i];
if (msg.toLowerCase().indexOf(name.toLowerCase()) !== -1) {
return agent_names[i];
}
}
return null;
关于javascript - 选择最长的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37693092/