用于Javascript正则表达式的转义字符串

too*_*php 469 javascript regex escaping

可能重复:
Javascript中是否有RegExp.escape函数?

我正在尝试根据用户输入构建一个javascript正则表达式:

function FindString(input) {
    var reg = new RegExp('' + input + '');
    // [snip] perform search
}

但是当用户输入包含一个?*因为它们被解释为正则表达式特殊时,正则表达式将无法正常工作.实际上,如果用户将不平衡([字符串放入其中,则正则表达式甚至无效.

什么是正确转义所有特殊字符以在正则表达式中使用的javascript函数?

Coo*_*J86 959

短暂的甜蜜

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

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
Run Code Online (Sandbox Code Playgroud)

安装

在npm上可用作escape-string-regexp

npm install --save escape-string-regexp
Run Code Online (Sandbox Code Playgroud)

注意

请参阅MDN:Javascript指南:正则表达式

其他符号(~`!@#...)可以不受影响地进行转义,但不是必须的.

.

.

.

.

测试用例:典型的网址

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"
Run Code Online (Sandbox Code Playgroud)

答案很长

如果你打算使用上面的函数,至少链接到你的代码文档中的这个堆栈溢出帖子,这样它看起来就像疯狂难以测试的伏都教.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());
Run Code Online (Sandbox Code Playgroud)

  • 哇,那很冗长.我更喜欢[bobince的版本](http://stackoverflow.com/a/3561711/157247).但是任何有效的东西都可以避免不必要的事情...... (20认同)
  • 大多数这些字符不需要在字符类中进行转义.短划线和正斜杠根本不需要转义.因此,这可以简化为:return str.replace(/ [[{}()*+?^ $ | \\] \.\\\]/g,"\\ $&"); (8认同)
  • 2016年有更好的方式吗? (8认同)
  • @SushantGupta"\\"添加新的反斜杠,它会转义匹配的特殊正则表达式字符."$&"是对当前模式匹配内容的反向引用,添加了原始的特殊正则表达式字符. (7认同)
  • 为什么它被'\\ $&'取代.那是什么意思?对不起,我是JS新手. (6认同)
  • 如果您已经在使用 lodash,则可以随时导入并使用 [`_.escapeRegExp()`](https://lodash.com/docs/4.17.15#escapeRegExp) (3认同)
  • 我希望所有的角色都应该被转义,而不仅仅是那些必须被转义的角色,这就是JSLint下面的东西. (2认同)
  • @Kal_Torak:var re = / [\ s \ S] * /; escapeRegExp(re.toString()); (2认同)