删除字符串中的非数字字符

问题描述 投票:0回答:13

我希望在 ASP.NET C# 中删除字符串中的非数字字符,即

40,595 p.a.
最终会变成
40595

c# asp.net
13个回答
354
投票

有很多方法,但这应该可以(虽然不知道它如何处理非常大的字符串):

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

94
投票

感觉很适合正则表达式。

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

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


10
投票

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

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

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

7
投票

另一种选择...

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

6
投票

使用仅捕获 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 也是一种选择


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

3
投票

从 C# 3.0 开始,您应该尽可能使用方法组代替 lambda 表达式。这是因为使用方法组会减少一次重定向,因此效率更高。

当前接受的答案将变为:

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

0
投票

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


0
投票

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

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
投票

接受的答案很好,但是它没有考虑 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());
    }

如需了解更多信息,请阅读我博客上的这篇文章


0
投票

如果您在 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

0
投票

删除所有非数字字符

Public Function OnlyNumeric(strIn As String) As String
      Try
            Return Regex.Replace(strIn, "[^0-9]", "")
      Catch
            Return String.Empty
      End Try
End Function
© www.soinside.com 2019 - 2024. All rights reserved.