正则表达式构造函数和文字之间的反斜杠差异
Backslash Discrepancy between Regex Constructor and Literals
标题总结了它。我在使用 new RegExp()
的正则表达式文字和构造函数之间转义反斜杠时遇到了一个奇怪的差异,我很好奇它背后的原因。
我试图在构造函数中转义括号 (
,如下所示:
var search = new RegExp('/(', 'g');
var result = "(test)".match(search);
但这一直返回错误。匹配在文字 /\(/g;
中运行良好,但在构造函数中我最终不得不做这样的事情:
search = new RegExp('\(', 'g');
有人可以向我解释为什么转义反斜杠需要构造函数中的转义反斜杠本身,而不是文字吗?
因为反斜杠在正则表达式上下文和字符串文字上下文中都是特殊字符。在正则表达式解析器可以看到它并应用它自己的特殊规则之前,您必须先了解字符串文字的特殊用法。
NOTE If pattern is a StringLiteral, the usual escape sequence substitutions are performed before the String is processed by RegExp. If pattern must contain an escape sequence to be recognised by RegExp, any backslash \ characters must be escaped within the StringLiteral to prevent them being removed when the contents of the StringLiteral are formed.
http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.4.1
标题总结了它。我在使用 new RegExp()
的正则表达式文字和构造函数之间转义反斜杠时遇到了一个奇怪的差异,我很好奇它背后的原因。
我试图在构造函数中转义括号 (
,如下所示:
var search = new RegExp('/(', 'g');
var result = "(test)".match(search);
但这一直返回错误。匹配在文字 /\(/g;
中运行良好,但在构造函数中我最终不得不做这样的事情:
search = new RegExp('\(', 'g');
有人可以向我解释为什么转义反斜杠需要构造函数中的转义反斜杠本身,而不是文字吗?
因为反斜杠在正则表达式上下文和字符串文字上下文中都是特殊字符。在正则表达式解析器可以看到它并应用它自己的特殊规则之前,您必须先了解字符串文字的特殊用法。
NOTE If pattern is a StringLiteral, the usual escape sequence substitutions are performed before the String is processed by RegExp. If pattern must contain an escape sequence to be recognised by RegExp, any backslash \ characters must be escaped within the StringLiteral to prevent them being removed when the contents of the StringLiteral are formed.
http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.4.1