Stripping out non-numeric characters in string

C#asp.net

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

Another option ...

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

Solution 7 - C#

 var output = new string(input.Where(char.IsNumber).ToArray());

Solution 8 - C#

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

Solution 9 - C#

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.

Solution 10 - C#

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

Solution 11 - C#

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 && !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 && !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 && !throwExceptionIfNull) 
            ? input 
            : new string(input.Where(c => char.IsLetterOrDigit(c)).ToArray());
    }

For additional info, read this post on my blog.

Solution 12 - C#

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 &= c
    End If
  Next c

  Return numberString
End Function

Solution 13 - C#

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

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
QuestionStevieBView Question on Stackoverflow
Solution 1 - C#Fredrik MörkView Answer on Stackoverflow
Solution 2 - C#Jonas ElfströmView Answer on Stackoverflow
Solution 3 - C#Ercan AyanView Answer on Stackoverflow
Solution 4 - C#Patrick CairnsView Answer on Stackoverflow
Solution 5 - C#OnkelborgView Answer on Stackoverflow
Solution 6 - C#kernowcodeView Answer on Stackoverflow
Solution 7 - C#EmreView Answer on Stackoverflow
Solution 8 - C#Tony BrownView Answer on Stackoverflow
Solution 9 - C#TimView Answer on Stackoverflow
Solution 10 - C#dhirschlView Answer on Stackoverflow
Solution 11 - C#DarksealView Answer on Stackoverflow
Solution 12 - C#Tony L.View Answer on Stackoverflow
Solution 13 - C#C BergsView Answer on Stackoverflow