在JavaScript中使用RegExp对象时要转义哪些字符? [英] Which characters to escape when using RegExp object in JavaScript?
问题描述
我有正则表达式 ^ \(\d + \)
,它用于匹配包含数字的括号,并且可以执行预期的操作。
I have the regex ^\(\d+\)
which is designed to match parentheses containing digits and which does what is expected.
我想扩展它以匹配括号中的数字,后跟一个空格,后跟一个来自变量的字符串。我知道我可以创建一个 RegExp
对象来执行此操作但是无法理解要转义哪些字符以使其工作。有人能向我解释这个吗?
I want to extend this to match digits in parentheses followed by a space followed by a string which comes from a variable. I know that I can crate a RegExp
object to do this but am having trouble understanding which characters to escape to get this to work. Is anybody able to explain this to me?
推荐答案
当你不使用 RegEx $ c时$ c>,您可以使用文字符号:
When you do not use RegEx
, you can use a literal notation:
/ ^ \(\d + \) /
但是当你使用RegEx 构造函数时,你需要双重转义这些符号:
But when you are using the RegEx constructor, you need to double escape these symbols:
var re = new RegExp(^ \\(\\\\ + \\));
有两种创建RegExp对象的方法:文字符号和
构造函数。要指示字符串,文本
表示法的参数不使用引号,而
构造函数的参数使用引号。
There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks.
...
当正则表达式保持不变时,使用文字表示法。
... Use literal notation when the regular expression will remain constant.
...
当您知道正则表达式模式将要改变,或者您不知道该模式并且正在获取它时,请使用构造函数来自
另一个来源,例如用户输入。
... 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.
现在,如果你有变量,这是个好主意坚持构造函数方法。
Now, in case you have a variable, it is a good idea to stick to the constructor method.
var re = new RegExp('^\\(\\d+\\) ' + variable);
逃避斜线是强制性的,因为它本身就是一个转义符号。
Escaping the slash is obligatory as it is itself is an escaping symbol.
这篇关于在JavaScript中使用RegExp对象时要转义哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!