-1

I have a data format coming from serial port as followinng :

4.99,2.34,25300\n

The application will be able to detect termination character (\n). The problem is I need to parse the message to extract each number.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
wbadry
  • 643
  • 11
  • 24

2 Answers2

1

I suggest using String.Split instead of regular expressions:

string data = @"4.99,2.34,25300\n";

List<double> numbers = data.Replace(@"\n", String.Empty)
                           .Split(",", StringSplitOptions.RemoveEmptyEntries)
                           .Select(x => double.Parse(x, CultureInfo.InvariantCulture))
                           .ToList();
Rui Jarimba
  • 9,732
  • 10
  • 46
  • 74
1

Using regular expressions:

string regex = @"(\d+(\.\d+)?),?";
string data = @"4.99,2.34,25300\n";

IEnumerable<double> numbers = from match in Regex.Matches(data, regex)
                              let number = match.Groups[1].Value
                              select double.Parse(number, CultureInfo.InvariantCulture);

foreach (double number in numbers)
{
    Console.WriteLine(number);
}

I am using parentesis to capture substrings within a match.

The first match 4.99,, as you can see from the screenshot has 3 groups:

  • the 1st group (index 0) matches everything: 4.99,
  • the 2nd group (index 1) matches the number 4.99 - this is what we want
  • the 3rd group matches the ,

Regular expression match groups

Rui Jarimba
  • 9,732
  • 10
  • 46
  • 74