javascript - 在 JavaScript 中使用 RegExp 对象时要转义哪些字符?

标签 javascript regex

我有一个正则表达式 ^\(\d+\),它被设计用来匹配包含数字的括号,并且它的作用符合预期。

我想扩展它以匹配括号中的数字,后跟一个空格,后跟一个来自变量的字符串。我知道我可以创建一个 RegExp 对象来执行此操作,但我无法理解要转义哪些字符才能使其正常工作。有人能给我解释一下吗?

最佳答案

当你不使用RegEx时,你可以使用literal notation:

/^\(\d+\)/

但是当你使用正则表达式构造函数时,你需要对这些符号进行双重转义:

var re = new RegExp("^\\(\\d+\\)");

MDN Reference :

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.

现在,如果您有一个变量,坚持使用构造函数方法是个好主意。

var re = new RegExp('^\\(\\d+\\) ' + variable);

转义斜线是必须的,因为它本身就是一个转义符号。

关于javascript - 在 JavaScript 中使用 RegExp 对象时要转义哪些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110479/

相关文章:

javascript - 通过 Ajax 从对话框发送 php 生成的表单数据

javascript - 正则表达式,字符串中#valueN#的所有条目

javascript - jquery 提交的表单返回 false;迷路了不能提交两次?

javascript - 为什么 JS 传播运算符不能与 Flow 精确类型一起使用

php - jquery ui的对话框

python - 如何从字符串中多次提取 HTML 标记模式?

javascript - 正则表达式(只有 1 点)

javascript - 正则表达式用于带有特定前置字符的HTML标记引号,并破坏HTML引号

javascript - 使用正则表达式从字符串中获取值

javascript - JS "for (var key in arr)"> 抛出我自己的 Array.prototypes,但不是固有的。为什么?