【问题标题】:Regex to match a exactly a word but accept a one-letter error正则表达式完全匹配一个单词但接受一个字母的错误
【发布时间】:2018-06-08 11:32:12
【问题描述】:

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

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

【问题讨论】:

  • 不,仅仅一个正则表达式不足以检查是否只有一个差异字母。有许多用于查找近处单词的库,并且有标准的单词距离(例如查找 Levenshtein),但没有什么比这更容易使用的了。
  • Regex 并不适合这个。您正在寻找像 SOUNDEX 这样的东西。我不认为它存在于原生 JavaScript 中,但可能有一些库支持它。
  • 感谢您的建议,我会去看看一切,我现在记得 Levenshtein 但不太记得之前是如何调用它来搜索它的

标签: javascript regex


【解决方案1】:

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

有一个自己的计算机科学分支处理这个problem,并且有很多算法。我建议使用已建立的 JavaScript 模糊搜索库之一,例如 Fuse.jsfuzzysearchfuzzyset.js

这是Fuse.js example

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多