首页 > 解决方案 > 我想使用javascript正则表达式在句子中查找单词(包括特殊字符)匹配

问题描述

我试过使用下面的代码。

var regex = new RegExp("\\b" + wordToMatch + "\\b", 'i'),
    wordToMatch = '$10',
    sentenseToSearch = "That book costs $10."
sentenseToSearch.match(regex);

如果 wordtoMatch = 'book' 或 'That' 或 'costs' 并且当 wordToMatch 为 "$10" 时匹配失败,它会起作用。撇号 (') 字符的问题相同。

前任:-

var regex = new RegExp("\\b" + wordToMatch + "\\b", 'i'),
    wordToMatch = 'Edward',
    sentenseToSearch = "He is Edward's father."
sentenseToSearch.match(regex);

上面的代码应该导致 null 因为句子中没有 Edward。但它匹配 Edward 的文本,不包括 's 字符。

我的代码适用于所有单词,除了包括特殊字符(如($、'、-等)的单词。有人可以帮我提供正则表达式来匹配包括特殊字符的单词。

标签: javascriptregex

解决方案


在正则表达式中将被视为文字字符串的用户输入转义——否则会被误认为是特殊字符——可以通过简单的替换来完成:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

测试代码:

function escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

var wordToMatch = '$10';
var sentenseToSearch = "That book costs $10.";
var regex = new RegExp(escapeRegExp(wordToMatch), 'i');
alert(sentenseToSearch.match(regex));


推荐阅读