【问题标题】:Stripping out non-numeric characters in string去除字符串中的非数字字符
【发布时间】:2011-04-28 00:14:03
【问题描述】:

我希望在 ASP.NET C# 中去除字符串中的非数字字符,即 40,595 p.a. 最终会变成 40595

谢谢

【问题讨论】:

标签: c# asp.net


【解决方案1】:

如果您在 VB 中工作并最终来到这里,“.Where”对我来说是一个错误。从这里得到这个: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

【讨论】:

    【解决方案2】:
    public static string RemoveNonNumeric(string value) => Regex.Replace(value, "[^0-9]", "");
    

    【讨论】:

    • 在我允许小数点后这对我有用。
    【解决方案3】:

    公认的答案很好,但它没有考虑 NULL 值,因此在大多数情况下都无法使用。

    这促使我改用这些辅助方法。第一个回答了 OP,而其他的可能对那些想要执行相反操作的人有用:

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

    如需了解更多信息,请在我的博客上read this post

    【讨论】:

      【解决方案4】:
       var output = new string(input.Where(char.IsNumber).ToArray());
      

      【讨论】:

        【解决方案5】:

        另一种选择...

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

        【讨论】:

        • 负数呢? (-) 减号不应该是其中的一部分吗?
        【解决方案6】:

        扩展方法将是更好的方法:

        public static string GetNumbers(this string text)
            {
                text = text ?? string.Empty;
                return new string(text.Where(p => char.IsDigit(p)).ToArray());
            }
        

        【讨论】:

        • 我更喜欢if (text == null) return string.Empty; 而不是text = text ?? string.Empty;。这样我们就不会降低性能。
        【解决方案7】:

        有很多方法,但应该这样做(虽然不知道它在处理非常大的字符串时如何执行):

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

        【讨论】:

        • 您可能应该使用IsDigit 而不是IsNumber"此方法[IsNumber] 确定Char 是否属于任何数字Unicode 类别。除了包括数字, 数字包括字符、分数、下标、上标、罗马数字、货币分子和带圆圈的数字。此方法与 IsDigit 方法形成对比,后者确定 Char 是否为基数 10 位。" msdn.microsoft.com/en-us/library/yk2b3t2y.aspx
        • @TrevorBrooks 假设您可以扩展条款:input.Where(c =&gt; char.IsDigit(c) || char.IsWhiteSpace(c))
        • 可以将其进一步简化为 return new string(input.Where(char.IsDigit).ToArray()); 。我只是让它更具可读性
        • 不错的答案。可能只是想考虑将函数从“GetNumbers”重命名为“GetDigits”......以明确其意图。
        • 也是一种很好的扩展方法。
        【解决方案8】:

        感觉很适合正则表达式。

        var s = "40,595 p.a.";
        var stripped = Regex.Replace(s, "[^0-9]", "");
        

        "[^0-9]" 可以替换为@"\D",但我喜欢[^0-9] 的可读性。

        【讨论】:

        • 我会同意,只要您对 .Net 中与正则表达式相关的开销感到满意
        • 出于好奇,这个答案和 Fredrik Mork 的答案之间的性能开销是多少?
        • 这可能比较慢,但唯一知道的方法是测量,因为它取决于 .NET 如何实现正则表达式、如何编译 Lambda 表达式等等。
        • 这比使用 IsDigit() 更灵活,因为您可以添加 '.'如果您想允许带小数位的数字,则将字符添加到正则表达式中。
        • 我在一个由 100,000 个 GUID 连接在一起(产生 3,600,000 个字符串)构成的字符串上对 Regex 与 LINQ 进行了简单的比较。 Regex 始终在半秒左右,而 LINQ 始终在 1/10 秒范围内。基本上 LINQ 平均快 5 倍或更多。
        【解决方案9】:

        下面是使用正则表达式的代码:

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

        【讨论】:

        • 我需要做什么才能让 Regex 工作得到这个错误 The name 'Regex' does not exist in the current context
        • 使用 System.Text.RegularExpressions;
        【解决方案10】:

        嗯,你知道数字是什么:0123456789,对吧?逐个字符遍历你的字符串;如果字符是数字,则将其附加到临时字符串的末尾,否则忽略。可能还有其他可用于 C# 字符串的辅助方法,但这是一种适用于任何地方的通用方法。

        【讨论】:

          【解决方案11】:

          使用仅捕获 0-9 并丢弃其余部分的正则表达式。正则表达式是第一次会花费很多的操作。或者做这样的事情:

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

          我想是这样的,不过我还没有编译..

          正如 Fredrik 所说,LINQ 也是一种选择

          【讨论】:

            猜你喜欢
            • 2018-10-21
            • 2012-04-28
            • 1970-01-01
            • 2010-12-24
            • 1970-01-01
            相关资源
            最近更新 更多