c# – Stripping out non-numeric characters in string

c# – Stripping out non-numeric characters in string

There are many ways, but this should do (dont know how it performs with really large strings though):

private static string GetNumbers(string input)
{
    return new string(input.Where(c => char.IsDigit(c)).ToArray());
}

Feels like a good fit for a regular expression.

var s = 40,595 p.a.;
var stripped = Regex.Replace(s, [^0-9], );

[^0-9] can be replaced by @D but I like the readability of [^0-9].

c# – Stripping out non-numeric characters in string

An extension method will be a better approach:

public static string GetNumbers(this string text)
    {
        text = text ?? string.Empty;
        return new string(text.Where(p => char.IsDigit(p)).ToArray());
    }

Leave a Reply

Your email address will not be published. Required fields are marked *