为什么正则表达式构造函数需要双重转义? [英] Why do regex constructors need to be double escaped?
问题描述
在下面的正则表达式中, \s
表示空格字符。我想这个正则表达式解析器正在遍历字符串并看到 \
并且知道下一个字符是特殊的。
In the regex below, \s
denotes a space character. I imagine the regex parser, is going through the string and sees \
and knows that the next character is special.
但事实并非如此,因为需要双重逃脱。
But this is not the case as double escapes are required.
为什么会这样?
var res = new RegExp('(\\s|^)' + foo).test(moo);
是否有一个具体的例子说明单个转义如何被误解为其他东西?
Is there a concrete example of how a single escape could be mis-interpreted as something else?
推荐答案
您正在通过将字符串传递给RegExp构造函数来构造正则表达式。
You are constructing the regular expression by passing a string to the RegExp constructor.
您需要转义 \
,以便您的字符串文字可以在将其转换为正则表达式之前将其表示为数据。
You need to escape the \
so that your string literal can express it as data before you transform it into a regular expression.
这篇关于为什么正则表达式构造函数需要双重转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!