Search code examples
c#stringparsingtext-parsing

Problem with Text field parsing to get data in C#


I receives data in this format.

var data="frame= 159 fps= 51 q=34.0 size= 512kB time=00:00:05.37 bitrate= 780.3kbits/s dup=3 drop=0 speed=1.72x";

To use the delimiter here the only possibility is space. But for that frame= 159 which has more spaces after = creating the problem. Same problem with frame, size, bitrate.

So I can't use either delimiter or simple string split i.e data.Split(" ")

How to parse values here to correct DTO/Object.

public class Template
{
   public float Frame {get;set;}
   public float Fps {get;set;}
   public string Size {get;set;}
   public TimeSpan Time {get;set;}
   public string Bitrate {get;set;}
   public short Dup {get;set;}
   public short Drop {get;set;}
   public string Speed {get;set;}
}

Solution

  • remove spaces after = using Regex

    var data = "frame=  159 fps= 51 q=34.0 size=     512kB time=00:00:05.37 bitrate= 780.3kbits/s dup=3 drop=0 speed=1.72x";
    data = Regex.Replace(data, @"=\s+", "=");
    foreach (var d in data.Split(' '))
    {
        var kv = d.Split('=');
        Console.WriteLine(String.Format("{0}: {1}", kv[0], kv[1]));
    }