正则表达式:验证长度,必须包含数字,必须包含 3 个连字符
我正在寻找用于验证电话号码的正则表达式。
以下是我希望我的正则表达式验证的内容:
- 长度必须为 14 到 17 个字符
- 必须全部为数字并包含 3 个连字符
接受的格式:
5-555-555-5555
55-55-555-5555
55-555-555-5555
555-555-555-5555
5555-555-555-5555
我当前的代码如下所示:
^.*(?=.{14,17})(?=.*\-{3,})(?=.*[\d\-]).*$
它允许超过 3 个连字符,长度为允许超过 17 个字符。
预先感谢您的帮助!
I'm looking for a regex for validating phone numbers.
Here is what I'd like my regex to validate:
- Must be 14 to 17 characters in length
- Must be all digits and contain 3 hyphens
Accepted formats:
5-555-555-5555
55-55-555-5555
55-555-555-5555
555-555-555-5555
5555-555-555-5555
My current code looks like this:
^.*(?=.{14,17})(?=.*\-{3,})(?=.*[\d\-]).*$
It is allowing more than 3 hyphens and the length is being allowed to exceed 17 characters.
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个丑陋的暴力版本,简单地明确列出了 4 种有效格式:
这是 Rubular 链接。
Here is an ugly brute force version that simply lists the 4 valid formats explicitly:
Here is the Rubular link.
这个怎么样:
How about this:
您可以尝试这个
(?=.{14,17})
首先使用前瞻断言字符串的长度在 14 到 17 个字符之间。然后匹配可以看到数字之间有三个连字符。^ 和 $
确保没有其他内容。You can try this one
(?=.{14,17})
first asserts using lookahead that the length of the string is in between 14 and 17 characters. Then it matches to see that there are three hyphens between the digits.^ and $
makes sure that there is nothing else.我知道这已经过时了,但我接受了挑战并制作了 Amber 答案的经过编辑的非暴力版本。
这能够强制执行格式 (x{1,4}-xxx-xxx-xxxx),并且比 Mark Wilkins 的答案更短。
Amber 的答案不完整,因为它不强制执行格式(当明确指出这不是有效格式时,5-555-555-5555555 将被验证),但它确实强制使用比 Narendra Yadala 的答案为 -1 字符的长度。
编辑(14/01/2014):
这是一个简化的答案:
我所做的很简单:我取消了前瞻。
在这种情况下它是没有用的。
这个答案比 Narendra Yadala 的答案长 -13 个字符,比我之前的答案长 -12 个字符。
I know this is old, but i took the challenge and made an edited non-bruteforce version of Amber's answer.
This has the ability to enforce format (x{1,4}-xxx-xxx-xxxx) and is shorter than Mark Wilkins' answer.
Amber's answer is incomplete cause it doesn't enforce format (5-555-555-5555555 is validated when it clearly states that isn't a valid format), but it does enforce length with -1 char than Narendra Yadala's answer.
EDIT (14/01/2014):
This is a reduced answer:
What i did was simple: i took away the lookahead.
It was useless in this case.
This one is -13 chars long that the Narendra Yadala's answer and -12 chars than my previous.