I am getting continuously changing data on my console using DataReceivedEventArgs event. Now I have to extract only the int
value of Total. for that I am using string function Substring()
I am using like below:
e.Data.Substring(7, e.Data.IndexOf("f"));
because no of total and fps are kept changing when it increase I am start losing the digit.
Please help to make it dynamic so whatever value lie between total and fps, I want to get it
Below is the data sample
Total= 1082 fps= 21 q=29.0 size= 6144kB time=00:00:36.33
CodePudding user response:
There are multiple ways to do this, ranging from easy to more difficult, the easiest it to use IndexOf("Total=")
and IndexOf("fps")
, like
Console.WriteLine(e.Data.Substring(e.Data.IndexOf("Total="), e.Data.IndexOf("fps")));
But that will break if the order of Total
, fps
, etc ever changes, so instead you can use RegEx, like
var input = "Total= 1082 fps= 21 q=29.0 size= 6144kB time=00:00:36.33";
var regexString = @"Total=(\s)*[0-9] ";
var regex = new Regex(regexString);
var match = regex.Match(input);
Console.WriteLine(match);
You could also build a parser and parse the data into a object, but that's out of scope for this answer.
P.S if you can change the source code of what's generating this event and data, you may want to think about not passing strings betweens parts of your application and instead pass objects and format those for console (or any other) presentation