Stripping out non-numeric characters in string

后端 未结 11 583
南旧
南旧 2021-01-30 09:46

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

相关标签:
11条回答
  • 2021-01-30 10:23

    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()); 
    
    0 讨论(0)
  • 2021-01-30 10:29

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

    0 讨论(0)
  • 2021-01-30 10:33
    public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");
    
    0 讨论(0)
  • 2021-01-30 10:35

    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
    
    0 讨论(0)
  • 2021-01-30 10:41

    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());
    }
    
    0 讨论(0)
提交回复
热议问题