Find and extract all numbers from the String

c#, numbers, regex, string

Solution

Your regex needs to be a little more complex to include decimals:

\d+(\.\d+)?

Then you need to get multiple matches:

MatchCollection mc = Regex.Matches(subjectString, "\\d+(\\.\\d+)?");
foreach (Match m in mc)
{
    double d = double.Parse(m.Groups[0].Value);
}

Here is an example.

Problem

I have a string like: "`Hello I'm 43 years old, I need 2 burgers each for 1.99$`". I need to parse it and get all the numbers in it as `double`. So the function should return an array of values like: `43, 2, 1.99`. In C++ I should've write all by myself, but C# has `Regex` and I think it may be helpful here: ``` String subjectString = "Hello I'm 43 years old, I need 2 burgers each for 1.99$"; resultString = Regex.Match(subjectString, @"\d+").Value; double result = double.Parse(resultString); ``` After this, the `resultString` is "43" and `result` is `43.0`. How to parse the string to get more numbers?

Original source

Related problems