How to extract decimal number from string in C#

Viewed 42112
string sentence = "X10 cats, Y20 dogs, 40 fish and 1 programmer.";
string[] digits = Regex.Split (sentence, @"\D+");

For this code I get these values in the digits array

10,20,40,1

string sentence = "X10.4 cats, Y20.5 dogs, 40 fish and 1 programmer.";
string[] digits = Regex.Split (sentence, @"\D+");

For this code I get these values in the digits array

10,4,20,5,40,1

But I would like to get like

10.4,20.5,40,1 as decimal numbers. How can I achieve this?

7 Answers

Credit for following goes to @code4life. All I added is a for loop for parsing the integers/decimals before returning.

    public string[] ExtractNumbersFromString(string input)
    {
        input = input.Replace(",", string.Empty);

        var numbers =  Regex.Split(input, @"[^0-9\.]+").Where(c => !String.IsNullOrEmpty(c) && c != ".").ToArray();

        for (int i = 0; i < numbers.Length; i++)
            numbers[i] = decimal.Parse(numbers[i]).ToString();

        return numbers;
    }
Related