首页 > 解决方案 > 正则表达式完全匹配一个单词但接受一个字母的错误

问题描述

我想知道是否有一种方法可以将单词与 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

但我希望在名称上使用这个系统,因为它们很容易拼写错误。

标签: javascriptregex

解决方案


您真正想要的是模糊字符串搜索/匹配。

计算机科学有一个自己的分支来处理这个问题,并且有很多算法。我建议使用已建立的 JavaScript 模糊搜索库之一,例如Fuse.jsfuzzysearch,或者可能是 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>


推荐阅读