1 Replies - 1542 Views - Last Post: 02 July 2012 - 08:18 AM

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1658
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Format US phone number with Regular Expressions

Posted 16 April 2008 - 08:49 AM

Description: Add a reference to System.Text.RegularExpressions, then pass the method the string you want formattedThis is a snippet I use when needing to format a US phone number into the format (555) 555-1212
//Namespace Reference
using System.Text.RegularExpressions

/// 
/// method to format a US phone number
/// 
/// phone number to format
/// 
public static string FormatUSPhone(string num)
{
    //first we must remove all non numeric characters
    num = num.Replace("(", "").Replace(")","").Replace("-","");
    string results = string.Empty;
    string formatPattern = @"(d{3})(d{3})(d{4})";
    results = Regex.Replace(num, formatPattern, "($1) $2-$3");
    //now return the formatted phone number
    return results;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Format US phone number with Regular Expressions

#2 ghendric  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 04-September 09

Re: Format US phone number with Regular Expressions

Posted 02 July 2012 - 08:18 AM

Instead of num = num.Replace("(", "").Replace(")","").Replace("-",""); try num = Regex.Replace(num, @"[^\p{Nd}]*", ""); You will get rid of any and all chars that aren't numeric..
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1