如果将正则表达式传递给"RegExp",会发生什么情况?构造函数? [英] What happens if you pass a regular expression to the "RegExp" constructor?

查看:315
本文介绍了如果将正则表达式传递给"RegExp",会发生什么情况?构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下正则表达式:

Let's say I have the following regular expression:

/hello\sworld\!/g

如果我将此正则表达式传递给RegExp构造函数,且不带引号:

If I pass this regular expression to the RegExp constructor, without quotation marks:

new RegExp(/hello\sworld\!/g)

它将返回包含/hello\sworld\!/g的正则表达式,如下所示:

Would it return a regular expression containing /hello\sworld\!/g, like this:

/\/hello\sworld\!\/\g/

还是会返回原始正则表达式?

Or would it return the original regular expression?

推荐答案

根据

According to MDN, the following expressions create the same regular expression:

new RegExp("ab+c", "i");
new RegExp(/ab+c/, "i");

预期结果:

/ab+c/i

如果您传递带有标志的正则表达式文字,但不在第二个参数中定义新标志,则结果也将相同,例如:

The result will also be the same if you pass a regex literal with a flag but don't define new flags in the second argument, for example:

new RegExp(/ab+c/i)

应返回相同的正则表达式文字(/ab+c/i),但如果确实指定了新的正则表达式标志(在第二个参数中),则所有现有标志都将被删除.

Should return the same regex literal (/ab+c/i), but if you do specify new regex flags (in the second argument) all existing flags will be removed.

new RegExp(/ab+c/i, "")
new RegExp(/ab+c/i, "g")
new RegExp(/ab+c/i, "m")

预期结果:

/ab+c/
/ab+c/g
/ab+c/m

字面意义是什么?

文字符号在评估表达式时提供了正则表达式的编译.

The literal notation provides a compilation of the regular expression when the expression is evaluated.

我什么时候应该使用文字符号?

When should I use the literal notation?

当正则表达式保持不变时,请使用文字表示法.例如,如果您使用文字符号构造循环中使用的正则表达式,则该正则表达式不会在每次迭代时重新编译.

Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

构造函数的作用是什么?

What does the constructor function do?

正则表达式对象的构造函数(例如,新的RegExp('ab+c'))提供正则表达式的运行时编译.

The constructor of the regular expression object (for example, new RegExp('ab+c')) provides runtime compilation of the regular expression.

何时应使用构造函数?

当您知道正则表达式模式将要更改,或者您不知道该模式并从其他来源(例如用户输入)获取该模式时,请使用构造函数.

Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

祝你好运.

这篇关于如果将正则表达式传递给"RegExp",会发生什么情况?构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆