如何在正则表达式中转义特殊字符 [英] How to escape special characters in regular expressions

查看:70
本文介绍了如何在正则表达式中转义特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的网站,我使用 dataTable 插件,并为用户提供了过滤结果的可能性.我实现了一些过滤器,该过滤器从结果中动态加载,并包含每一列的所有不同值.

For my website I use the dataTable plugin and to give the user the possibility to filter the results. I implemented some filter, which are dynamically loaded from the results and contains the all different values of each column.

由于可以组合多个过滤器,因此我停用了智能搜索,而不得不启用了regEx-search.所有这些事情都很好.

As more than one filter can be combined, I deactived the smart search and had to active the regEx-search instead. All these things are working fine.

我的问题是:我有内容(其他内容)"之类的内容,对于包含方括号的内容,搜索无效(未找到结果).

My Problem is: I have content like "content (another content)", and for those contents containing brackets, the search doesn't work (no result is found).

是否可以在调用之前屏蔽 searchString :

Is there a possibility to mask the searchString before calling:

table.column('myColumn:name').search(searchString, true, false, true).draw();

我尝试将字符串替换为"\)"或类似的东西,但这无济于事.如果我只删除那些特殊字符,则由于regEx搜索需要精确的字符串,因此也找不到结果.

I tried to replace the string with "\)" or something like this, but that doesn't help. If I just delete those special characters the results can't be found either as regEx search needs exact strings.

有人可以帮我吗?

推荐答案

解决方案

您可以添加并使用函数 escapeRegExp()来转义特殊字符 MDN-正则表达式文章中找到的字符:

You can add and use a function escapeRegExp() that will escape special characters as found in MDN - Regular Expressions article:

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

// ... skipped ...

table.column('myColumn:name').search(escapeRegExp(searchString), true, false, true).draw();

演示

有关代码和演示,请参见此jsFiddle .

See this jsFiddle for code and demonstration.

这篇关于如何在正则表达式中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆