简体   繁体   English

用于验证电话号码的正则表达式模式

[英]Regex pattern for Validating phone number

I have a input string ("My phone number is 860-678 - 2345"). 我有一个输入字符串(“我的电话号码是860-678-2345”)。 From the input string I need to validate phone number using Regex. 从输入字符串中,我需要使用Regex验证电话号码。

I am using the below pattern but it doesn't work if the phone number contains white Space in it. 我正在使用以下模式,但是如果电话号码中包含空格,则该模式将不起作用。

[(]?[2-9]{1}[0-9]{2}[)-. ,]?[2-9]{1}[0-9]{2}[-. ,]?[0-9]{4}

Thanks. 谢谢。

The following regular expression: 以下正则表达式:

(\([2-9]\d\d\)|[2-9]\d\d) ?[-.,]? ?[2-9]\d\d ?[-.,]? ?\d{4}

matches all of the following: 符合以下所有条件:

860-678-2345
(860) 678-2345
(860) 678 - 2345

and probably a fair amount else too. 可能还有很多其他的。 Broken down: 细分:

  • (\\([2-9]\\d\\d\\)|[2-9]\\d\\d) - Matches the first part of the number with or without brackets (\\([2-9]\\d\\d\\)|[2-9]\\d\\d) -匹配数字的第一部分,带或不带括号
  • ?[-.,]? ? - A hyphen, period (or full stop to us Brits) or a comma, with or without surrounding spaces. -连字符,句号(或对我们英国人来说是句号)或逗号,带或不带周围的空格。
  • [2-9]\\d\\d - Matches the second part of the number. [2-9]\\d\\d匹配数字的第二部分。
  • \\d{4} - Matches the final part of the number. \\d{4} -匹配数字的最后部分。

\\d\\d and [0-9]{2} are equivalent; \\d\\d[0-9]{2}是等效的; the former is just slightly shorter so improves readability. 前者稍短一些,因此提高了可读性。 Likewise, [2-9] and [2-9]{1} are equivalent; 同样, [2-9][2-9]{1}是等效的; the {1} just means "one instance of the preceeding pattern", which is a given anyway. {1}仅表示“先前模式的一个实例”,无论如何都是给定的。

You could check for spaces seperately before and after the seperating charactors. 您可以在分离的字符之前和之后分别检查空格。

[(]?[2-9]{1}[0-9]{2}[ ]?[)-.,]?[ ]?[2-9]{1}[0-9]{2}[ ]?[-.,]?[ ]?[0-9]{4}

Keep in mind, this wont actually match the parens so something like (234-567, 1234 would match. So if you want more strict matching, you will need a much more complicated regex or code the validation using something else. 请记住,这实际上不会匹配括号,因此类似(234-567, 1234匹配。因此,如果您想要更严格的匹配,则将需要更复杂的正则表达式或使用其他代码来编写验证。

最好的办法是先去除所有空白,然后,您可以轻松地使用已完成的RE验证您的数字。

This might help you: 这可能对您有帮助:

(?\\d{3})?-? (?\\ d {3})? - ? *\\d{3}-? * \\ d {3} - ? *-?\\d{4} * - ?\\ d {4}

Refer: Regular Expression Liberary 参考:正则表达式自由

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

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