Allow Only Numbers In A String - C#

Often you may have user input that needs to only be numbers, and the input doesn’t allow characters.  There is javascript that you can put on the front end to limit what keystrokes can be made in an input field; however, there are still ways around it.  Here’s a good filter method that you can pass a string to, that will return to you only the numerical characters.  It strips out all of the stuff that you don’t want. 

So, if you passed (or user inputed): 18009995DAN, it would filter it to 18009995

 

    private string FilterNumbers(string unformattedNumber)

    {

       string numberExtractorExpression = @"(\d+\.?\d*|\.\d+)";

 

       MatchCollection formattedNumber = Regex.Matches(unformattedNumber, numberExtractorExpression);

 

       StringBuilder numbers = new StringBuilder();

 

       for( int i = 0; i != formattedNumber.Count; ++i )

       {

            numbers.Append(formattedNumber[i].Value);

       }

 

       return numbers.ToString();

    }