gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:59:39 26 4
gpt4 key购买 nike

我有一个正则表达式 ^\(\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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com