gpt4 book ai didi

javascript - 如何在正则表达式值或值中添加注释?

转载 作者:行者123 更新时间:2023-11-27 22:33:27 36 4
gpt4 key购买 nike

在声明值时我们可以这样做:

var x, // comment
y, // comment
z; // comment

没关系。我有这个稍微长一点的 regExp (我仍在向 regExp 介绍自己),我不习惯这样做,但它有效

var pattern = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\-\s]?\d{4}$/;

但是当我尝试像在变量声明示例中那样做时:

var pattern = /^(1\s?)? // optional 1 with space or nonspace; also optional
(\(\d{3}\)|\d{3}) // optional () bracket in 3 digits
[\s\-]? // optional space and dash
\d{3} // 3 digits
[\-\s]?
\d{4}$/; // 4 digits

上面的代码不起作用,但我只想出于学习目的这样做。可以吗?

最佳答案

您可以尝试通过连接字符串数组来构建正则表达式:

var pattern = new RegExp([
"(\\(\d{3}\\)|\\d{3})", // optional () bracket in 3 digits
"[\\s\\-]?", // optional space and dash
"\\d{3}", // 3 digits
"[\\-\\s]?",
"\\d{4}$/" // 4 digits
].join(""));

当然,这不是很优雅,因为它需要转义所有这些斜杠。

编辑:实际上,您可以通过创建一个 RegExp 数组而不是字符串,然后连接它们来避免这些斜杠转义业务:

var pattern = new RegExp([
/^(1\s?)?/, // optional 1 with space or nonspace; also optional
/(\(\d{3}\)|\d{3})/, // optional () bracket in 3 digits
/[\s\-]?/, // optional space and dash
/\d{3}/, // 3 digits
/[\-\s]?/,
/\d{4}$/ // 4 digits
].map(function(x) {return x.source}).join(""));

这需要使用 map 执行额外步骤,将每个 RegExp 转换回字符串。

关于javascript - 如何在正则表达式值或值中添加注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39355662/

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