asp.net – Stripping out non-numeric characters in string

The Question :

125 people think this question is useful

Hey Im looking to strip out non-numeric characters in a string in ASP.NET C#

So i.e 40,595 p.a.

would end up with 40595

Thanks

The Question Comments :

The Answer 1

256 people think this answer is useful

There are many ways, but this should do (don’t 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());
}

The Answer 2

64 people think this answer is useful

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

The Answer 3

8 people think this answer is useful

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());
    }

The Answer 4

6 people think this answer is useful

Use either a regular expression that’s only capturing 0-9 and throws away the rest. A regular expression is an operation that’s going to cost a lot the first time though. Or do something like this:

var sb = new StringBuilder();
var goodChars = "0123456789".ToCharArray();
var input = "40,595";
foreach(var c in input)
{
  if(goodChars.IndexOf(c) >= 0)
    sb.Append(c);
}
var output = sb.ToString();

Something like that I think, I haven’t compiled though..

LINQ is, as Fredrik said, also an option

The Answer 5

4 people think this answer is useful

Another option …

private static string RemoveNonNumberDigitsAndCharacters(string text)
{
    var numericChars = "0123456789,.".ToCharArray();
    return new String(text.Where(c => numericChars.Any(n => n == c)).ToArray());
}

The Answer 6

3 people think this answer is useful
public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");

The Answer 7

0 people think this answer is useful

Well, you know what the digits are: 0123456789, right? Traverse your string character-by-character; if the character is a digit tack it onto the end of a temp string, otherwise ignore. There may be other helper methods available for C# strings but this is a generic approach that works everywhere.

The Answer 8

0 people think this answer is useful

Here is the code using Regular Expressions:

string str = "40,595 p.a.";

StringBuilder convert = new StringBuilder();

string pattern = @"\d+";
Regex regex = new Regex(pattern);

MatchCollection matches = regex.Matches(str);

foreach (Match match in matches)
{
convert.Append(match.Groups[0].ToString());
}

int value = Convert.ToInt32(convert.ToString()); 

The Answer 9

0 people think this answer is useful

The accepted answer is great, however it doesn’t take NULL values into account, thus making it unusable in most scenarios.

This drove me into using these helper methods instead. The first one answers the OP, while the others may be useful for those who want to perform the opposite:

    /// <summary>
    /// Strips out non-numeric characters in string, returning only digits
    /// ref.: https://stackoverflow.com/questions/3977497/stripping-out-non-numeric-characters-in-string
    /// </summary>
    /// <param name="input">the input string</param>
    /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
    /// <returns>the input string numeric part: for example, if input is "XYZ1234A5U6" it will return "123456"</returns>
    public static string GetNumbers(string input, bool throwExceptionIfNull = false)
    {
        return (input == null &amp;&amp; !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsDigit(c)).ToArray());
    }

    /// <summary>
    /// Strips out numeric and special characters in string, returning only letters
    /// </summary>
    /// <param name="input">the input string</param>
    /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
    /// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZAU"</returns>
    public static string GetLetters(string input, bool throwExceptionIfNull = false)
    {
        return (input == null &amp;&amp; !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsLetter(c)).ToArray());
    }

    /// <summary>
    /// Strips out any non-numeric/non-digit character in string, returning only letters and numbers
    /// </summary>
    /// <param name="input">the input string</param>
    /// <param name="throwExceptionIfNull">if set to TRUE it will throw an exception if the input string is null, otherwise it will return null as well.</param>
    /// <returns>the letters contained within the input string: for example, if input is "XYZ1234A5U6~()" it will return "XYZ1234A5U6"</returns>
    public static string GetLettersAndNumbers(string input, bool throwExceptionIfNull = false)
    {
        return (input == null &amp;&amp; !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsLetterOrDigit(c)).ToArray());
    }

For additional info, read this post on my blog.

The Answer 10

0 people think this answer is useful

If you’re working in VB and ended up here, the “.Where” threw an error for me. Got this from here: https://forums.asp.net/t/1067058.aspx?Trimming+a+string+to+remove+special+non+numeric+characters

Function ParseDigits(ByVal inputString as String) As String
  Dim numberString As String = ""
  If inputString = Nothing Then Return numberString

  For Each c As Char In inputString.ToCharArray()
    If c.IsDigit Then
      numberString &amp;= c
    End If
  Next c

  Return numberString
End Function

The Answer 11

-1 people think this answer is useful
 var output = new string(input.Where(char.IsNumber).ToArray());

Tags:

Add a Comment