简体   繁体   English

使用正则表达式验证我们的电话号码

[英]Validate us number with regular expression

I'm doing an exercise on freecodecamp for validate us telephone number. 我正在freecodecamp上进行练习,以验证我们的电话号码。

The user may fill out the form field any way they choose as long as it is a valid US number. 用户可以选择任何方式填写表单字段,只要它是有效的美国号码即可。 The following are all valid formats for US numbers: 以下是美国号码的所有有效格式:

555-555-5555, (555)555-5555, (555) 555-5555, 555 555 5555, 5555555555, 1 555 555 5555 555-555-5555,(555)555-5555,(555)555-5555、555 555 5555、5555555555、1 555 555 5555

I'm using RegEx to test input.I type these expression on regex101 我正在使用RegEx来测试输入。我在regex101上键入这些表达式

(([1]\s)?(\()*(\d{3})(-|\)|\)\s|\s)*(\d{3})(-|\s)*\d{4})

to test input like: 测试输入如下:

2 ** (757) 622-7382** return true 2 **(757)622-7382 **返回true

- 1 (757) 622-7382 return true -1(757)622-7382返回true

10 ** (757) 622-7382** return true 10 **(757)622-7382 **返回true

How could I test the leading 2, minus sign and 10. 我如何测试前导2,减号和10。

I would suggest you to have a look on OWASP Validation Regex Repository as they are subject of validation and continuous updates 我建议您看一下OWASP验证正则表达式存储库,因为它们是验证和持续更新的主题

For the US Phone (at the time I'm writing)the suggested RegEx is ^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$ 对于美国电话(在撰写本文时),建议的RegEx为^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$

((-)?\\d{0,2} )? Notice the space after {0,2} 注意{0,2}之后的space

(-)?       // may begin with a minus
(\d{1,2})?   // may have 1 or 2 digits before the actual number
( )?       // may have a space after that

DEMO 演示

Here is a modified version of your regex that will now match the new phone formats: 这是您的正则表达式的修改版本,现在可以与新的电话格式匹配:

^[-+]?(?:\d{1,2}\s)?\(*(?:\d{3})(?:-|\)|\)\s|\s)*\d{3}(?:-|\s)*\d{4}$

See demo 观看演示

Note I removed the capture groups (I doubt you need them, and they create additional overhead) and added optional + or - before the number. 注意我删除了捕获组(我怀疑您是否需要它们,并且它们会增加额外的开销),并在数字之前添加了可选的+- Also, \\d{1,2} matches 1 or 2 digits due to the limiting quantifier {1,2} . 同样,由于限制量 {1,2}\\d{1,2}匹配1或2位数字

Might be a bit late but here is the solution to this one. 可能会晚一点,但是这是解决方法。

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

You do want to have the ^ at the beginning of the expression to match the first char of the string and you want to use $ at the end to let the expression know that this is the end. 您确实希望表达式的开头有^来匹配字符串的第一个字符,并且您想在结尾使用$来使表达式知道这是结尾。

You can see the above answer and another way of doing it on the following github github link 您可以在以下github github链接上查看以上答案以及另一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM