Normalize phone numbers with regular expression

I have a list of phone numbers entered by users without verification, and they look like this:

 - 495) 995-0595
 - 105-6439
 - 095 268 8621
 - 324-51-44
 - 7 (495) 995-05-95
 - 7 495 995 05 95
 - 7 (495) 995-0595
 - +7 (495) 995-05-95
 - 7 (495)925-34-89
 - 7(495)9253489
 - 7(495)925-34-89
 - 74959950595

I want to convert these numbers to this (Russian) format: + X (XXX) XXX-XX-XX

Is there any chance to achieve this using regular expressions?

+5
source share
5 answers

Yup, Extract and Reformat!

List<string> oldlist = new List<string>();
List<string> newlist = new List<string>();
foreach(string s in oldlist)
{
     if(s.Contains('(')) s = s.Replace('('), "");//etc
     newlist.Add(numFormat(s));
}

string prefix = "495";

string numFormat(string s)
{
     string my;
     if(s.Length == 7)
     {
         my = string.Format("+7 ({0}) {1} {2} {3}", prefix, s.substring(0,3), s.subtring(3,2), s.substring(5,2);
     }
     else if(s.length == 10)
     {
         my = string.Format("+7 ({0}) {1} {2} {3}", s.substring(0,3), s.substring(3,3), s.subtring(5,2), s.substring(7,2);        
     }
     //etc
     return my;
}

It's not at all in my head ... but you get the idea

+3
source

Run your list:

var strippedNumbers = new List<string>();
foreach (var num in listOfRussianNumbers.Select(x=>Regex.Replace(x, "[^0-9]", ""))) 
    strippedNumbers.Add(num.Length == 7?"7499"+num:num);

Then use string.Format to print as you want

string.Format("+{0} ({1}) {2}-{3}-{4}", 
    num.Substring(0,1), 
    num.Substring(1,3),
num.Substring(4,3),
num.Substring(7,2),
num.Substring(9,2));
+2
source

,

  • .
  • Loop , . Char.IsDigit() .
  • string.Substring().

, .

string str = "495) 995-0595";
List<char> digits = new List<char>();

for (int i = 0; i < str.Length; i++)
{
    if(char.IsDigit(str[i]))
        digits.Add(str[i]);
}

str = new string(digits.ToArray());

str = "+" + str.Substring(0, 1) + " (" + str.Substring(1, 3) + ") " 
      + str.Substring(4, 2) + "-" + str.Substring(6, 2) + "-" + str.Substring(8);

"+4 (959) 95-05-95"

+1

This is the best I can get as soon as possible.

((\+?\d)\s?)?\(?(\d\d\d)\)?\s?(\d\d\d)(\s|-)?(\d\d)(\s|-)?(\d\d)

This will select the boldface from your sample.

495) 995-0595
105-6439
095 268 8621
324-51-44
7 (495) 995-05-95
7 495 995 05 95
7 (495) 995-0595
+7 (495) 995-05-95
7 (495 ) 925-34-89
7 (495) 9253489
7 (495) 925-34-89
74959950595

In lines that do not match, you can send them through another procedure or for manual processing.

+1
source

Something like that:

(\d)? ?\(?(\d\d\d)?\)? *?(\d\d\d) *?-? *?(\d\d) *?-? *?(\d\d)
0
source

All Articles