kyrisu
kyrisu

Reputation: 4653

Parse the number with Regex with non capturing group

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.

Upvotes: 0

Views: 1906

Answers (2)

Rashmi Pandit
Rashmi Pandit

Reputation: 23868

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]);

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158409

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?).

Upvotes: 2

Related Questions