tags:

views:

317

answers:

2

Hi,

I'm trying to parse phone number with regex. Exactly I want to get a string with phone number in it using function like this:

string phoneRegex = @"^([+]|00)(\d{2,12}(?:\s*-*)){1,5}$";
string formated = Regex.Match(e.Value.ToString(), phoneRegex).Value;

As you can see I'm trying to use non-capturing group (?:\s*-*) but I'm doing something wrong.

Expected resoult should be:

input (e.Value): +48 123 234 344 or +48 123234344 or +48 123-234-345

output: +48123234344

Thanks in advance for any suggestions.

+2  A: 

Regex.Match will not alter the string for you; it will simply match it. If you have a phone number string and want to format it by removing unwanted characters, you will want to use the Regex.Replace method:

// pattern for matching anything that is not '+' or a decimal digit
string replaceRegex = @"[^+\d]";
string formated = Regex.Replace("+48 123 234 344", replaceRegex, string.Empty);

In my sample the phone number is hard-coded, but it's just for demonstration purposes.

As a side note; the regex that you have in your code sample above assumes that the country code is 2 digits; this may not be the case. The United States has a one digit code (1) and many countries have 3-digit codes (perhaps there are countries with more digits than that, as well?).

Fredrik Mörk
You are right, I think I just expected to much from regex :P .. and yes I'm trying to make phone number format international (different country codes are supported later in the code).
kyrisu
A: 

This should work:

Match m = Regex.Match(s, @"^([+]|00)\(?(\d{3})\)?[\s\-]?(\d{3})\-?(\d{4})$");
return String.Format("{0}{1}{2}{4}", m.Groups[1], m.Groups[2], m.Groups[3], m.Groups[3]);
Rashmi Pandit