简体   繁体   English

正则表达式与特殊字符匹配

[英]RegEx match with special characters

I have a string.match condition that was working until I realized that some words are " personal(computer) " have special characters like parentheses in the word. 我有一个string.match条件一直起作用,直到我意识到某些单词是“ personal(computer)在单词中带有括号之类的特殊字符。 For example my code is grabbing the term to compare to which would be "personal(computer)" and searching through data to find any instance of that, but by using 例如,我的代码抓取要与之比较的术语“个人(计算机)”,然后搜索数据以查找该实例的任何实例,但是使用

string1.match(stringtarget,"ig"); //returns null 

I am a novice with regex, so how could I fix this to work for special characters as well. 我是regex的新手,因此如何解决此问题以使其适用于特殊字符。

If you don't need the regular expression features, you can use indexOf : 如果不需要正则表达式功能,则可以使用indexOf

if (string1.toLowerCase().indexOf(stringtarget.toLowerCase()) >= 0) {
    // It's in there
}

Otherwise (and I'm guessing you're using match for a reason!), you'll have to pre-process the stringtarget to escape any special characters. 否则(并且我猜您正在使用match是有原因的!),您必须对stringtarget进行预处理,以转义任何特殊字符。

For instance, this is a function I used in a recent project to do exactly that, which is inspired by a similar PHP function: 例如,这是我在最近的项目中使用的一个功能,正是出于类似的PHP函数的启发:

if (!RegExp.escape) {
    (function() {
        // This is drawn from http://phpjs.org/functions/preg_quote:491
        RegExp.escape = RegExp_escape;
        function RegExp_escape(str) {
            return String(str).replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1');
        }
    })();
}

And so: 所以:

var match = string1.match(RegExp.escape(stringtarget),"ig");

您可以使用preg_quote javascript端口转义正则表达式特定的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM