Javascript regexp文字和构造函数之间的差异 [英] Differences between Javascript regexp literal and constructor
问题描述
我们最近有一个错误,在一位开发人员将一个RegExp文字改为构造函数调用后,我想知道为什么会有任何差异。
具体代码是
We recently had a bug, after a fellow developer changed a RegExp literal into a constructor call, and I was wondering why there is any difference at all. The exact code was
var parts = new RegExp("/rt:([^@]+)@(\d+)/").exec(tag);
vs原始
var parts = /rt:([^@]+)@(\d+)/.exec(tag);
当标签
是,例如 rt:60C1C036-42FA-4073-B10B-1969BD2358FB @ 00000000077
,第一个(错误)调用返回 null
,而第二个一个返回 [rt:60C1C036-42FA-4073-B10B-1969BD2358FB @ 00000000077,60C1C036-42FA-4073-B10B-1969BD2358FB,00000000077]
When tag
is, for example rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077
, the first (buggy) call returns null
, while the second one returns["rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077", "60C1C036-42FA-4073-B10B-1969BD2358FB", "00000000077"]
毋庸置疑,我还原了这一变化,但我想知道为什么首先会出现这样的差异。
Needless to say, I reverted the change, but I'd like to know why is there such a difference in the first place.
推荐答案
有两个问题:
/
不表达式的一部分。它们是分隔符,标记正则表达式文字。如果你使用 RegExp
,则必须删除它们,否则它们按字面意思匹配斜杠。
The /
are not part of the expression. They are delimiters, marking a regex literal. They have to be removed if you use RegExp
, otherwise they match a slash literally.
其次,反斜杠是字符串文字中的转义字符。要为表达式创建文字 \
,您必须在字符串中对其进行转义。
Secondly, the backslash is the escape character in string literals. To create a literal \
for the expression, you have to escape it in the string.
因此,相当于:
new RegExp("rt:([^@]+)@(\\d+)")
特别是逃避使得表达更加困难如果你想使用 RegExp
,写。实际上只有在想要动态创建表达式时才需要它,例如,如果要包含存储在变量中的文本。如果你有一个固定的表达式,文字 /.../
更容易编写,更简洁。
Especially the escaping makes expression a bit more difficult to write if you want to use RegExp
. It is actually only needed if you want to create expression dynamically, that is, if you want to include text stored in a variable for example. If you have a fixed expression, a literal /.../
is easier to write and more concise.
这篇关于Javascript regexp文字和构造函数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!