Parse number using regex with no capturing group

I am trying to parse a phone number with a regex. I want to get a string with a phone number in it using the following function:

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

      

As you can see, I am trying to use a non-capturing group (?: \ S * - *), but I am doing something wrong.

The expected link should be:

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

: +48123234344

Thanks in advance for any suggestions.

0


a source to share


2 answers


Regex.Match won't change the line for you; it will just match it. If you have a phone number and want to format it by removing unnecessary 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 example, the phone number is hardcoded, but it is for demonstration purposes only.

As a side note; the regex you have in the above code example assumes 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 (maybe there are countries with more digits than that?).

+2


a source


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

      

0


a source







All Articles