您的分隔符版本非常接近。粗略地说*,您只是在前瞻中丢失了),而在实际匹配中丢失了第一个-。 (顺便说一句,第一个$ 也是多余的。)
假设您希望同时允许123-456-7890 和 (123)-456-7890,则工作的* 正则表达式为:
正则表达式 1
^\(?(\d)(?!\1{2}\)?-\1{3}-\1{4})\d{2}\)?-\d{3}-\d{4}$
| |_| ||_
| | | |
| missed (optional) ')' | missed '-'
| |
'?' required to make '(' and ')' optional
Demo ?
如果您还希望允许1234567890 和(123)4567890,则需要将连字符设为可选。请注意,在实际匹配中,您必须使用捕获组和反向引用“链接”两个连字符,否则123-4567890、123456-7890 等也会匹配:
正则表达式 2
^\(?(\d)(?!\1{2}\)?-?\1{3}-?\1{4})\d{2}\)?(-)?\d{3}\2\d{4}$
| | |__| ||
optional hypens | back reference to captured hypen
|
optional captured hypen
*警告:
(123-456-7890 和 123)-456-7890(以及第二个正则表达式的 (1234567890 和 123)4567890)都是允许的。如果您希望排除这些,则在正则表达式的开头需要积极的前瞻 (?=\(\d{3}\)|\d{3}[^)]):
正则表达式 1a
^(?=\(\d{3}\)|\d{3}[^)])\(?(\d)(?!\1{2}\)?-\1{3}-\1{4})\d{2}\)?-\d{3}-\d{4}$
|_____________________||_________________________________________________|
| |
positive lookahead Regex 1
正则表达式 2a
^(?=\(\d{3}\)|\d{3}[^)])\(?(\d)(?!\1{2}\)?-?\1{3}-?\1{4})\d{2}\)?(-)?\d{3}\2\d{4}$
|_____________________||_______________________________________________________|
| |
positive lookahead Regex 2
正向预测
^(?=\(\d{3}\)|\d{3}[^)])
|_______| |_______|
| |
| or starts with 3 digits, then no ")"
|
Either starts with "(", then 3 digits, then ")"