正则表达式不适用于 once 或 none

Regex expression not working with once or none

下面是我的正则表达式:

[^4\d{3}-?\d{4}-?\d{4}-?\d{4}$]

但它在 - 处抛出错误。我正在使用 ?,它应该允许 - 出现零次或一次。为什么会报错?

尝试使用 \ 转义 - 并删除 []:

^4\d{3}\-?\d{4}\-?\d{4}\-?\d{4}$

正则表达式的问题是模式包含在 [] 中,它们被视为字符 class 标记(参见 Character Classes or Character Sets):

With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae].

在字符 classes 中,- 在文字字符之间创建范围。在您的情况下,这些范围无效(从具有较高值的​​字符到具有较低值的字符),因为 {4} 和其他子模式被视为单独的字符,而不是特殊结构:

所以,你需要做的就是移除两边的[]

^4\d{3}-?\d{4}-?\d{4}-?\d{4}$

参见 regex demo