去掉字符串中的非数字字符

时间:2022-06-24 09:58:19

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

嘿,我想去掉ASP字符串中的非数字字符。净c#

So i.e 40,595 p.a.

所以我。40595年利e。

would end up with 40595

结果是40595吗

Thanks

谢谢

9 个解决方案

#1


156  

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

#2


41  

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 - 9]”可以取代了@“\ D”,但我喜欢的可读性(^ 0 - 9)。

#3


5  

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:

使用一个只捕获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();

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

像这样的东西我想,我还没有编译过。

LINQ is, as Fredrik said, also an option

正如弗雷德里克所说,LINQ也是一种选择

#4


5  

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

#5


1  

Another option ...

另一种选择……

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

#6


0  

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.

你知道数字是多少,0123456789,对吧?遍历字符串逐字符;如果字符是数字,则将其附加到临时字符串的末尾,否则忽略。c#字符串可能有其他的帮助器方法,但是这是一种通用的方法,可以在任何地方使用。

#7


0  

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

#8


0  

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:

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

    /// <summary>
    /// Strips out non-numeric characters in string, returning only digits
    /// ref.: https://*.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.

如需更多信息,请阅读本文。

#9


-1  

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

#1


156  

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

#2


41  

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 - 9]”可以取代了@“\ D”,但我喜欢的可读性(^ 0 - 9)。

#3


5  

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:

使用一个只捕获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();

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

像这样的东西我想,我还没有编译过。

LINQ is, as Fredrik said, also an option

正如弗雷德里克所说,LINQ也是一种选择

#4


5  

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

#5


1  

Another option ...

另一种选择……

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

#6


0  

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.

你知道数字是多少,0123456789,对吧?遍历字符串逐字符;如果字符是数字,则将其附加到临时字符串的末尾,否则忽略。c#字符串可能有其他的帮助器方法,但是这是一种通用的方法,可以在任何地方使用。

#7


0  

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

#8


0  

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:

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

    /// <summary>
    /// Strips out non-numeric characters in string, returning only digits
    /// ref.: https://*.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.

如需更多信息,请阅读本文。

#9


-1  

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