3

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?

Netherwire
  • 2,669
  • 3
  • 31
  • 54

3 Answers3

5

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.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
2

Try to use the following regular expression:

-?[0-9]+(\.[0-9]+)?

and then use Regex.Matches and iterate over the matches returned.

1

You should use Matches method to get a collection of matches. Also, you need to add dot to your regex

String subjectString = "Hello I'm 43 years old, I need 2 burgers each for 1.99$";
var matches = Regex.Matches(subjectString, @"\d+(\.\d+)?");

for (int i = 0; i < matches.Count; i++ )
{
    double d = double.Parse(matches[i].Value);
}
Szymon
  • 42,577
  • 16
  • 96
  • 114