c#从字符串中提取多个数字

时间:2021-10-19 20:07:21

I'm trying to extract whole numbers of different length from a string with lots of formatting. The string in question could look like this:

我正在尝试从具有大量格式的字符串中提取不同长度的整数。有问题的字符串可能如下所示:

string s = "Hallo (221122321 434334 more text3434 even mor,34343 343421.343sf 343";

The output I'm looking for is an array of:

我正在寻找的输出是一个数组:

{221122321,434334,3434,34343,343421,343,343}

2 个解决方案

#1


24  

var result = new Regex(@"\d+").Matches(s)
                              .Cast<Match>()
                              .Select(m => Int32.Parse(m.Value))
                              .ToArray();

#2


-1  

Use a foreach loop like this:

使用这样的foreach循环:

string result = "";

foreach (string str in s)
{
    int number;
    if (int.TryParse(str, out number))
       result += s;
    else
       result += ",";
}

#1


24  

var result = new Regex(@"\d+").Matches(s)
                              .Cast<Match>()
                              .Select(m => Int32.Parse(m.Value))
                              .ToArray();

#2


-1  

Use a foreach loop like this:

使用这样的foreach循环:

string result = "";

foreach (string str in s)
{
    int number;
    if (int.TryParse(str, out number))
       result += s;
    else
       result += ",";
}