Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phone number regular expression

Tags:

regex

I am reviewing the c# code of an application and documenting. While going through the code, I seen an unusual regular expression for US Phone Number. The regular expression is below

 @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";

My conclusion from the above phone number would be like 01.(29).123.4567 or 01-38-111-1111.

Am I interpreting correctly? Any insight into that regular expression is highly appreciated. Examples for above regular expression would help me to learn more about regular expressions.

like image 297
SPAdmin Avatar asked Dec 22 '22 08:12

SPAdmin


1 Answers

Reading left to right...

  • ^[01]? May possibly start with 0 or 1.
  • [- .]? May possibly be followed with a -, space or ..
  • (([2-9]\d{2})|[2-9]\d{2}) Must start with a digit between 2 and 9 and then be followed by any two digits. (This is strangely repeated twice, and the capturing groups should always contain the same portion, weird). This may have meant to have escaped the parenthesis, which would make more sense. Generally, you use the \ character to escape.
  • [- .]? May possibly be followed with a -, space or ..
  • \d{3} Must be followed by any three digits.
  • [- .]? May possibly be followed with a -, space or ..
  • \d{4}$ Must be followed (and end) with any four digits.
like image 155
alex Avatar answered Dec 24 '22 01:12

alex