Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 244,263 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,252 people online right now. Registration is fast and FREE... Join Now!





Format US phone number with Regular Expressions

This is a snippet I use when needing to format a US phone number into the format (555) 555-1212

Submitted By: PsychoCoder
Actions:
Rating:
Views: 7,104

Language: C#

Last Modified: April 16, 2008
Instructions: Add a reference to System.Text.RegularExpressions, then pass the method the string you want formatted

Snippet


  1. //Namespace Reference
  2. using System.Text.RegularExpressions
  3.  
  4. /// <summary>
  5. /// method to format a US phone number
  6. /// </summary>
  7. /// <param name="num">phone number to format</param>
  8. /// <returns></returns>
  9. public static string FormatUSPhone(string num)
  10. {
  11.     //first we must remove all non numeric characters
  12.     num = num.Replace("(", "").Replace(")","").Replace("-","");
  13.     string results = string.Empty;
  14.     string formatPattern = @"(\d{3})(\d{3})(\d{4})";
  15.     results = Regex.Replace(num, formatPattern, "($1) $2-$3");
  16.     //now return the formatted phone number
  17.     return results;
  18. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month