To remove non numeric characters from alpha numeric string by using Regex, to do this we can use regular expressions, have a look at below code snippet.
Regex exculdePattern = new Regex(@"[^.0-9]", RegexOptions.Compiled); if (exculdePattern.IsMatch(phoneNumber)) { phoneNumber = exculdePattern.Replace(phoneNumber, string.Empty); }
If the phone number is alpha numeric, the above code snippet replaces all non numeric characters with empty.
The below pattern removes a specific character i.e. hyphen(-).
Regex exculdePattern = new Regex(@"[-]+", RegexOptions.Compiled);
To verify the phone number is a numeric and minumum length, the below numeric pattern helps.
Regex numericPattern = new Regex(@"\d{10}$", RegexOptions.Compiled); if (numericPattern.IsMatch(phoneNumber)) { double phoneNum = Convert.ToDouble(phoneNumber); Console.Write("\n"+phoneNum.ToString("(###) ###-####")); phoneNumber = string.Concat(phoneNumber.Substring(0, 3), "-",
phoneNumber.Substring(3, 3), "-", phoneNumber.Substring(6, 4)); Console.Write("\n" + phoneNumber); }