javascript - 在短语数组和字符串变量之间创建一个完全匹配的数组
问题描述
我有一系列短语,例如:
let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
我有一个字符串变量,例如:
let speechResult = 'i was sent to mars and earth i wanted i love'
我想根据数组中短语和字符串变量的完全匹配创建一个新数组。
上述示例的预期结果将是:
let newArr = [ 'i was sent', 'i love'];
注意:代码的性能很重要!
更新:我这样做了,但这有两个问题:
-第一:我没有得到预期结果的顺序。
-第二:没有完全匹配,所以我根本没有得到预期的结果。
let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
let speechResult = 'i was sent to mars and earth i wanted i love'
let newArr = [];
for(let i = 0; i < structures.length; i++ ){
if(speechResult.includes(structures[i])){
newArr.push(structures[i]);
}
}
console.log(newArr)
解决方案
这基本上很容易通过过滤来解决:
let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
let speechResult = 'i was sent to mars and earth i wanted i love'
const newArr = structures.filter((structure) => speechResult.includes(structure));
console.log(newArr);
但正如您所看到的,“我想要”也包含(因为 SpeechResult 包含“我想要”)。因此,我们必须使用正则表达式来排除此类部分命中:
let structures = ['to earth' ,'to protect you', 'i do', 'i love', 'i was sent', 'i want'];
let speechResult = 'i was sent to mars and earth i wanted i love'
const newArr = structures.filter((structure) => {
const rg = new RegExp(`(${structure})(?![a-z]+)`,'gi');
return speechResult.match(rg);
});
console.log(newArr);
这会给我们正确的结果(我会说非常有效)。
推荐阅读
- javafx - JavaFX| .setWrapText() 不在 TextArea 中换行
- sql - 用于查找和抑制数字和特殊字符的 SQL 代码
- javascript - 如何使用jquery删除维度关联数组中的数组
- python - 在 Django 中发布博客之前先获得管理员的批准
- javascript - 无法将 php 变量传递给 javascript:SyntaxError: "" 字符串文字包含未转义的换行符
- python - 按列阅读列表
- android - 在应用程序后台运行后,Application onCreate() 中完成的工作是否仍然存在?
- sql - 存在重复时连接表
- c# - 如何同时运行 navmesh 代理和 raycast?
- r - 将 p 值的星添加到相关矩阵 R