Javascript regexp 字面量和构造函数之间的差异 [英] Differences between Javascript regexp literal and constructor
问题描述
我们最近遇到了一个错误,在一位开发人员将 RegExp 文字更改为构造函数调用之后,我想知道为什么会有任何区别.确切的代码是
var parts = new RegExp("/rt:([^@]+)@(d+)/").exec(tag);
对比原版
var parts =/rt:([^@]+)@(d+)/.exec(tag);
当 tag
为例如 rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077
时,第一个(有问题的)调用返回 null代码>,而第二个返回<代码>["rt:60C1C036-42FA-4073-B10B-1969BD2358FB@00000000077", "60C1C036-42FA-4073-B10B-1969BD230007"
>
不用说,我恢复了更改,但我想知道为什么首先会有如此大的差异.
有两个问题:
/
是表达式的不是的一部分.它们是分隔符,标记一个正则表达式文字.如果您使用 RegExp
,则必须删除它们,否则它们会按字面意思匹配斜杠.
其次,反斜杠是字符串文字中的转义字符.要为表达式创建文字 ,您必须在字符串中对其进行转义.
因此,相当于:
new RegExp("rt:([^@]+)@(\d+)")
<小时>
特别是如果您想使用 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 the original of
var parts = /rt:([^@]+)@(d+)/.exec(tag);
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.
There are two problems:
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.
Thus, the equivalent would be:
new RegExp("rt:([^@]+)@(\d+)")
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屋!