问题描述:

This question already has an answer here:

  • A comprehensive regex for phone number validation

    36 answers

网友答案:

Try this one (using look-aheads to match parenthesis and other balance checks):

^(?:((?=\(.*\).*\-)|(?!.*\()(?!.*\)))\(?[0-9]{3}\)?(((?<=[)])|[\-\s])(?=.*\-)|\.(?=.*\.)|(?<=^)|(?=[0-9]+$)))?[0-9]{3}[\s.-]?[0-9]{4}$

Or this one (using \d as this is my contestant to the shortest-regex parade):

^((\d{3}-|\(\d{3}\)\s?)?\d{3}-|^\d{3}(\.)?\d{3}\3)\d{4}$
网友答案:

Regex

^\d{10}|^(\(\d{3}\)\s?)?\d{3}-\d{4}$|^\d{3}([.-])\d{3}\2\d{4}$

Matches the following

1234567890
123-456-7890
123.456.7890
(123)456-7890
(123) 456-7890
456-7890

Does not match on

123-45-6789
123:4567890
123/456-7890
(123-456-7890
123.456-7890
(123)456.7890
网友答案:

This pattern works with your examples, i write it without the java escapes:

 ^(?>\(\d{3}\) ?|\d{3}[.-]?)?\d{3}[.-]?\d{4}$

Explanations:

 ^                 begining  of the string
 (?>               open an atomic group
    \(\d{3}\) ?    3 digits with parenthesis followed by a space or not
   |               OR
    \d{3}[.-]      3 digits followed by . or - or not
 )                 close atomic group
 ?                 the atomic group is optional
 \d{3}             3 digits
 [.-]?             followed by a . or a - (optional)
 \d{4}             4 digits
 $                 end of the string         
相关阅读:
Top