7

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 Answers 2

24
var result = new Regex(@"\d+").Matches(s)
                              .Cast<Match>()
                              .Select(m => Int32.Parse(m.Value))
                              .ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent solution, but I'd change .OfType<Match> to .Cast<Match> to better indicate that I expect all the match items to actually be of type Match (they cannot be any other type).
Wouldn't you want to change m => m.Value to m => Int32.Parse(m.Value) so you have an array of int, instead of an array of string? (There are no quotes in the desired output.)
Very Elegant Solutions, now even better after the update !
-1

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 += ",";
}

1 Comment

This will not work, also will not result in a array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.