Reputation: 343
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?
Upvotes: 1
Views: 127
Reputation: 163277
Another option is to use a pattern with a capture group, and get the group value.
\b([0-9]+(?:\.[0-9]+)?) fps\b
\b
A word boundary to prevent a partial match(
Capture group 1
[0-9]+(?:\.[0-9]+)?
Match 1+ digits 0-9 with an optional decimal part)
Close group 1 fps
Match literally\b
A word boundarySee a regex demo and a C# demo.
For example
string s = " 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)";
Match m = Regex.Match(s, @"\b([0-9]+(?:\.[0-9]+)?) fps\b");
if (m.Success) {
Console.WriteLine(m.Groups[1].Value);
}
Output
29.97
Upvotes: 0
Reputation: 11977
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.
Upvotes: 4