c# Extract multiple numbers from a string

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}

Upvotes: 7

Views: 1546

Answers (2)

decPL
decPL

Reputation: 5402

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

Upvotes: 24

user790025
user790025

Reputation: 7

Use a foreach loop like this:

string result = "";

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

Upvotes: -1

Related Questions