Stripping out non-numeric characters in string

Viewed 126481

I'm looking to strip out non-numeric characters in a string in ASP.NET C#, i.e. 40,595 p.a. would end up as 40595.

Thanks

13 Answers
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");

Strips out all non Numeric characters

Public Function OnlyNumeric(strIn As String) As String
      Try
            Return Regex.Replace(strIn, "[^0-9]", "")
      Catch
            Return String.Empty
      End Try
End Function

As of C# 3.0, you should use method groups in lieu of lambda expressions where possible. This is because using method groups results in one less redirect, and is thus more efficient.

The currently accepted answer would thus become:

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