Search code examples
c#stringsubstringindexof

C# get the position of a whitespace before a special char


I am trying to extract the FPS count from a string. This string and the FPS count can be of different structure and length.

Two Examples would be:

"  Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 480x480 [SAR 1:1 DAR 1:1], 868 kb/s, 29.97 fps, 29.97 tbr, 11988 tbn (default)"
"  Stream #0:0: Video: msmpeg4v3 (MP43 / 0x3334504D), yuv420p, 320x240, 744 kb/s, SAR 1:1 DAR 4:3, 29.97 fps, 29.97 tbr, 29.97 tbn"

The only constant for getting the location of the FPS count is the " fps" and the ", " part in front of the number in the string.

I can get the location of the " fps" with this: processOutput.IndexOf(" fps").

But because the FPS count can be of different length, I can not use this: processOutput.Substring(fpslocation - 5, 5);

Is there a way to get the position of the ", " part before the number? Then I could take that as start index and the position of the " fps" part as end index. Or can this value be filtered out even more easily?


Solution

  • You can use a regular expession for this:

    var match = Regex.Match(input, @"[\d\.]+(?= fps)")
    

    will look for a sequence of digits and decimal points ([\d\.]+) followed by " fps"; the latter not being included in the match.

    match.Value will then contain the number.