Replace non-numeric with empty string


Quick add on requirement in our project. A field in our DB to hold a phone number is set to only allow 10 characters. So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow?


10/10/2017 10:07:19 AM

Accepted Answer

Definitely regex:

string CleanPhone(string phone)
    Regex digitsOnly = new Regex(@"[^\d]");   
    return digitsOnly.Replace(phone, "");

or within a class to avoid re-creating the regex all the time:

private static Regex digitsOnly = new Regex(@"[^\d]");   

public static string CleanPhone(string phone)
    return digitsOnly.Replace(phone, "");

Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).

1/22/2009 7:58:04 PM

You can do it easily with regex:

string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow