C# 从字符串中提取数字以创建仅数字字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11002527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:04:25  来源:igfitidea点击:

Extract numbers from string to create digit only string

c#.netregexstring

提问by kevp

I have been given some poorly formatted data and need to pull numbers out of strings. I'm not sure what the best way to do this is. The numbers can be any length.

我收到了一些格式不正确的数据,需要从字符串中提取数字。我不确定这样做的最佳方法是什么。数字可以是任意长度。

string a = "557222]]>";
string b = "5100870<br>";

any idea what I can do so I'll get this:

知道我能做什么,所以我会得到这个:

a = "557222"
b = "5100870"

Thanks

谢谢

Solution is for c# sorry. Edited the question to have that tag

解决方案是为 c# 抱歉。编辑问题以具有该标签

采纳答案by Jason McCreary

Not familiar enough with .NET for exact code. Nonetheless, two approaches would be:

对 .NET 的确切代码不够熟悉。尽管如此,两种方法是:

  • Cast it as an integer. If the non-digit characters are at the end (i.e. 21389abc), this is the easiest.
  • If you have intermixed non-digit characters (i.e. 1231a23v) and want to keep everydigit, use the regex [^\d]to replace non-digit characters.
  • 将其转换为整数。如果非数字字符在末尾(即21389abc),这是最简单的。
  • 如果您混合了非数字字符(即1231a23v)并希望保留每个数字,请使用正则表达式[^\d]替换非数字字符。

回答by Reed Copsey

You could write a simple method to extract out all non-digit characters, though this won't handle floating point data:

您可以编写一个简单的方法来提取所有非数字字符,尽管这不会处理浮点数据:

public string ExtractNumber(string original)
{
     return new string(original.Where(c => Char.IsDigit(c)).ToArray());
}

This purely pulls out the "digits" - you could also use Char.IsNumberinstead of Char.IsDigit, depending on the result you wish.

这纯粹是提取“数字” - 您也可以使用Char.IsNumber而不是Char.IsDigit,具体取决于您希望的结果。

回答by Ethan Brown

You can use a simple regular expression:

您可以使用一个简单的正则表达式:

var numericPart = Regex.Match( a, "\d+" ).Value;

If you need it to be an actual numeric value, you can then use int.Parseor int.TryParse.

如果您需要将其作为实际数值,则可以使用int.Parseint.TryParse

回答by Olivier Jacot-Descombes

Try this

尝试这个

string number = Regex.Match("12345<br>", @"\d+").Value;

This will return the first group of digits. Example: for the input "a 123 b 456 c"it will return "123".

这将返回第一组数字。示例:对于输入"a 123 b 456 c",它将返回"123".

回答by Atters

The question doesn't explicitly state that you just want the characters 0 to 9 but it wouldn't be a stretch to believe that is true from your example set and comments. So here is the code that does that.

该问题没有明确说明您只想要字符 0 到 9,但从您的示例集和评论中相信这是真的,这并不难。所以这是执行此操作的代码。

        string digitsOnly = String.Empty;
        foreach (char c in s)
        {
            // Do not use IsDigit as it will include more than the characters 0 through to 9
            if (c >= '0' && c <= '9') digitsOnly += c;
        }

Why you don't want to use Char.IsDigit() - Numbers include characters such as fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits.

为什么不想使用 Char.IsDigit() - 数字包括诸如分数、下标、上标、罗马数字、货币分子、带圆圈的数字和特定于脚本的数字等字符。

回答by Milind Raut

Try this oneliner:

试试这个oneliner:

Regex.Replace(str, "[^0-9 _]", "");

回答by soroxis

You could use LINQ. The code below filters the string into an IEnumerable with only digits and then converts it to a char[]. The string constructor can then convert the char[] into a string:

你可以使用 LINQ。下面的代码将字符串过滤为只有数字的 IEnumerable,然后将其转换为 char[]。然后字符串构造函数可以将 char[] 转换为字符串:

string a = "557222]]>";
string b = "5100870<br>";

a = new string(a.Where(x => char.IsDigit(x)).ToArray());
b = new string(b.Where(x => char.IsDigit(x)).ToArray());

回答by Michael Bahig

Here's the version that worked for my case

这是适用于我的案例的版本

    public static string ExtractNumbers(this string source)
    {
        if (String.IsNullOrWhiteSpace(source))
            return string.Empty;
        var number = Regex.Match(source, @"\d+");
        if (number != null)
            return number.Value;
        else
            return string.Empty;
    }