Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a normalized phone number to a user-friendly version

In my C# application, I use a regular expression to validate the basic format of a US phone number to make sure that the user isn't just entering bogus data. Then, I strip out everything except numbers, so this:

(123) 456-7890 x1234

becomes

12345678901234

in the database. In various parts of my application, however, I would like to convert this normalized phone number back to

(123) 456-7890 x1234

What's the best way to do such a thing? (Don't worry about accounting for international phone number formats, by the way.)

like image 429
David Brown Avatar asked Jan 08 '09 20:01

David Brown


People also ask

What is a normalized phone number?

Phone number normalization is used to translate a phone number into a standard, or normal, form. If numbers are not normalized, it is difficult to compare two phone numbers to see if they are the same. By changing all numbers into a normal form, Streem Center can check and handle them efficiently.


2 Answers

String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))

Will result in (123) 456-7890 x 123

like image 190
BFree Avatar answered Oct 22 '22 00:10

BFree


Using a regex you can replace:

(\d{3})(\d{3})(\d{4})(\d{4})

with:

(\1) \2-\3 x\4

(Though I'm not familiar with US phone numbers so maybe there's more to it.)

like image 25
PEZ Avatar answered Oct 22 '22 00:10

PEZ