javascript - 我想使用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 字符。
我的代码适用于所有单词,除了包括特殊字符(如($、'、-等)的单词。有人可以帮我提供正则表达式来匹配包括特殊字符的单词。
解决方案
在正则表达式中将被视为文字字符串的用户输入转义——否则会被误认为是特殊字符——可以通过简单的替换来完成:
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));
推荐阅读
- c# - 获取 ComboBox 选定项
- php - 列中的 Wordpress 搜索结果
- components - Flutter AppBar 多次使用组件
- odoo - 在odoo视图中显示动态值?
- amazon-web-services - 是否每个 aws 批处理作业都会启动一个新的 docker 容器
- nginx - 使用 Nginx 上下文路由通过 https 运行 Zeppelin
- javascript - 以角度创建一个库以用于任何项目
- c++ - 如何初始化由 unique_ptr 管理的数组元素?
- android - 如何在 RecyclerView PagedListAdapter 的特定位置添加 Admob?
- twitter-bootstrap - 为什么我的按钮有不同的颜色而它们有相同的类