Replace non-numeric with empty string

C#RegexStringPhone Number

C# Problem Overview


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?

Regex?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

You can do it easily with regex:

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

Solution 3 - C#

You don't need to use Regex.

phone = new String(phone.Where(c => char.IsDigit(c)).ToArray())

Solution 4 - C#

Here's the extension method way of doing it.

public static class Extensions
{
    public static string ToDigitsOnly(this string input)
    {
        Regex digitsOnly = new Regex(@"[^\d]");
        return digitsOnly.Replace(input, "");
    }
}

Solution 5 - C#

Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:

phoneNumber  = Regex.Replace(phoneNumber, "\\D", String.Empty);

Solution 6 - C#

How about an extension method that doesn't use regex.

If you do stick to one of the Regex options at least use RegexOptions.Compiled in the static variable.

public static string ToDigitsOnly(this string input)
{
    return new String(input.Where(char.IsDigit).ToArray());
}

This builds on Usman Zafar's answer converted to a method group.

Solution 7 - C#

for the best performance and lower memory consumption , try this:

using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;

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

    public static void Main()
    {
        Console.WriteLine("Init...");

        string phone = "001-12-34-56-78-90";

        var sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            DigitsOnly(phone);
        }
        sw.Stop();
        Console.WriteLine("Time: " + sw.ElapsedMilliseconds);

        var sw2 = new Stopwatch();
        sw2.Start();
        for (int i = 0; i < 1000000; i++)
        {
            DigitsOnlyRegex(phone);
        }
        sw2.Stop();
        Console.WriteLine("Time: " + sw2.ElapsedMilliseconds);
    
        Console.ReadLine();
    }

    public static string DigitsOnly(string phone, string replace = null)
    {
        if (replace == null) replace = "";
        if (phone == null) return null;
        var result = new StringBuilder(phone.Length);
        foreach (char c in phone)
            if (c >= '0' && c <= '9')
                result.Append(c);
            else
            {
                result.Append(replace);
            }
        return result.ToString();
    }

    public static string DigitsOnlyRegex(string phone)
    {
        return digitsOnly.Replace(phone, "");
    }
}

The result in my computer is:
Init...
Time: 307
Time: 2178

Solution 8 - C#

I'm sure there's a more efficient way to do it, but I would probably do this:

string getTenDigitNumber(string input)
{    
    StringBuilder sb = new StringBuilder();
    for(int i - 0; i < input.Length; i++)
    {
        int junk;
        if(int.TryParse(input[i], ref junk))
            sb.Append(input[i]);
    }
    return sb.ToString();
}

Solution 9 - C#

try this

public static string cleanPhone(string inVal)
        {
            char[] newPhon = new char[inVal.Length];
            int i = 0;
            foreach (char c in inVal)
                if (c.CompareTo('0') > 0 && c.CompareTo('9') < 0)
                    newPhon[i++] = c;
            return newPhon.ToString();
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt DawdyView Question on Stackoverflow
Solution 1 - C#Joel CoehoornView Answer on Stackoverflow
Solution 2 - C#Christian C. SalvadóView Answer on Stackoverflow
Solution 3 - C#Usman ZafarView Answer on Stackoverflow
Solution 4 - C#AaronView Answer on Stackoverflow
Solution 5 - C#Wes MasonView Answer on Stackoverflow
Solution 6 - C#Michael LangView Answer on Stackoverflow
Solution 7 - C#Max-PCView Answer on Stackoverflow
Solution 8 - C#Jon NortonView Answer on Stackoverflow
Solution 9 - C#Charles BretanaView Answer on Stackoverflow