-3

I have a line from which I need to extract a Name and the result (double) of that name.

The line looks like this:

James: 8, John: 8, Jasmin: 12, Igor: 1.54, Garry: 0, Gabe: 0.12, Lauren: 0, Grace: 81.31

I need each of them as an array of Name and Amount.

I tried to use regex but quite failed. Any assistance is much appreciated.

Gkills
  • 587
  • 1
  • 6
  • 28
Oran Band
  • 1
  • 1

2 Answers2

2

As the comment says, you don't need regex, just split. Something like that works:

string str = "James: 8, John: 8, Jasmin: 12, Igor: 1.54, Garry: 0, Gabe: 0.12, Lauren: 0, Grace: 81.31";
var values = str.Split(',');
(string name, double value)[] result = new (string, double)[values.Length];
for (int i = 0; i < values.Length; i++)
{
    var splittedValue = values[i].Split(':');
    result[i] = (splittedValue[0], Double.Parse(splittedValue[1], CultureInfo.InvariantCulture));
}
Thibaut
  • 342
  • 1
  • 7
0

As the line is regular you can get away with one split:

string str = "James: 8, John: 8, Jasmin: 12, Igor: 1.54, Garry: 0, Gabe: 0.12, Lauren: 0, Grace: 81.31";

var values = str.Split(',',':');
(string name, double value)[] result = new (string, double)[values.Length/2];
for (int i = 0; i < values.Length; i+=2)
    result[i/2] = (values[i].Trim(), Convert.ToDouble(values[i+1]));
Caius Jard
  • 72,509
  • 5
  • 49
  • 80