代码之家  ›  专栏  ›  技术社区  ›  Anonymous

如果我使用变量而不是直接使用相应的字符串,为什么这个正则表达式不起作用?

  •  0
  • Anonymous  · 技术社区  · 7 年前

    function escape(str) {
      return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\\\$&');
    }
    
    function replace(str, needle, replacement) {
      var expr = '([^\\[]*)(' +
          escape(needle) + ')([^\\]]*)';
      return str.replace(new RegExp(expr, 'g'), '$1' + replacement + '$3');
    }
    
    document.body.innerHTML += replace('hello() [hello()] test()', '()', '@');
    

    问题在于以下几行:

    var expr = '([^\\[]*)(' +
      escape(needle) + ')([^\\]]*)';
    

    如果我用

    var expr = '([^\\[]*)(' +
      '\\(\\)' + ')([^\\]]*)';
    

    它起作用了。我不明白为什么返回值 escape \\(\\) 如果我用

    alert(escape('()'));
    

    不工作的小提琴: https://jsfiddle.net/rmof8pzv/
    工作小提琴: https://jsfiddle.net/gpoy2rbt/

    2 回复  |  直到 7 年前
        1
  •  1
  •   Ivar    7 年前

    看来你把你的反斜杠的逃逸搞混了。

    您需要以字符串文字转义反斜杠,因为反斜杠也用于转义其他字符。这意味着字符串 字面意义的 '\\' 存储为 \

    console.log('\\');

    在正则表达式中,还需要用一个反斜杠转义字符,但如果用字符串文字转义字符,则出于上述原因,需要对其进行双重转义。这就是为什么您的工作示例有效。但是在你的 escape() '\\\\$&' '\\$&' 它应该很好用。

    function escape(str) {
      return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
    }
    
    function replace(str, needle, replacement) {
      var expr = '([^\\[]*)(' +
          escape(needle) + ')([^\\]]*)';
      return str.replace(new RegExp(expr, 'g'), '$1' + replacement + '$3');
    }
    
    console.log(replace('hello() [hello()] test()', '()', '@'));
        2
  •  1
  •   lenilsondc    7 年前

    问题来自于双反斜杠在 escape 作用 '\\\\$&' 你不需要逃避,因为它只需要像这样逃避一次 '\\$&' . 所以改变转义函数给了我预期的结果。

    function escape(str) {
      return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
    }