javascript - 正则表达式完全匹配一个单词但接受一个字母的错误
问题描述
我想知道是否有一种方法可以将单词与 javascript 中的正则表达式匹配,但这可以接受一个拼写错误(一个字母更改、一个丢失的字母或一个更多的字母)。
例子。在这里,我有一个完全匹配:
function isWordInSentence(s, w) {
s = s.toLowerCase();
w = w.toLowerCase();
return new RegExp('\\b'+w+'\\b').test(s);
}
var word = 'bird';
console.log(isWordInSentence('I like my bird', word)); //True
console.log(isWordInSentence('I use thunderbird', word)); //False
这个案子已经不可能了,但我想要一些可以接受这些事情的东西:
console.log(isWordInSentence('I like my birds', word)); //True
console.log(isWordInSentence('I like my birdd', word)); //True
console.log(isWordInSentence('I like my beard', word)); //False
console.log(isWordInSentence('I use thunderbird', word)); //False
我知道基本语言可能会带来很多像这样的误报:
console.log(isWordInSentence('Do you bid?', word)); //True
但我希望在名称上使用这个系统,因为它们很容易拼写错误。
解决方案
您真正想要的是模糊字符串搜索/匹配。
计算机科学有一个自己的分支来处理这个问题,并且有很多算法。我建议使用已建立的 JavaScript 模糊搜索库之一,例如Fuse.js、fuzzysearch,或者可能是 blurset.js。
这是一个Fuse.js 示例:
var books = [{
'ISBN': 'A',
'title': "Old Man's War",
'author': 'John Scalzi'
}, {
'ISBN': 'B',
'title': 'The Lock Artist',
'author': 'Steve Hamilton'
}]
var options = {
keys: ['title', 'author'],
id: 'title'
}
var fuse = new Fuse(books, options)
console.log(fuse.search('ol\' man'));
console.log(fuse.search('Locke'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js"></script>
推荐阅读
- python - 我如何创建调用相互中断的函数的热键?
- java - 休息:如何处理数千个相同的请求
- node.js - Angular 源文件在浏览器中可见。如何隐藏?
- javascript - Slick Carousel - 在移动设备上幻灯片中的 5 个项目到 1 个项目
- python-3.x - 尝试获取占位符详细信息时如何访问幻灯片的形状元素?这是使用 Python PPTX 完成的
- javascript - 在 v-for 循环中访问元素的数据 (Vue.js)
- php - 为什么 Laravel 提供默认时间戳?
- django - Django Formset Validation - Formset 中的总和值
- r - 如何在 r 中创建一个新的键值对
- java - 为什么jar的父文件夹也出现在引用的库中?