Sometimes, we need to remove all special characters from a mobile number and store just numbers only. The simplest way to do so is, look for the special characters and remove them from the number.
Here is a method that removes special characters, space, +, and - from a number. You can use the same approach to remove any character a number. If your string has other characters, add them to this list.
- private string convert_to_number(string No)
- {
- string mobileno = "";
- //remove special characters
- foreach (char ch in No)
- {
- if (ch != ' ' && ch != '+' && ch != '-')
- {
- mobileno = mobileno + ch.ToString();
- }
- }
- //convert to 10 digit
- if (mobileno.Length > 10)
- {
- mobileno = mobileno.Substring(mobileno.Length - 10, 10);
- }
- return (mobileno);
- }
- Regular expression:
- / ^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$/ (without +91 or 0)
- /^((\\+91-?)|0)?[0-9]{10}$/ (with or without +91 or 0)
- ^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$/ (split the number and the country code)

Jin NecesarioPosted Aug 21, 2019, 3:47 AM
Nice article. However; I do personally prefer "regular expressions".
Lajapathy ArunPosted Mar 20, 2013, 4:57 AM
Use regex, just it will be one line code. Dont write too much of code for validation.