I'm New in Regex
programming and I want to search for a pattern example:
19:09:41 PM : [ 0] 0.0-100.2 sec 796 MBytes 66.6 Mbits/sec 0.273 ms 2454161/3029570 (81%) --> I want 66
18:55:13 PM : [ 0] 0.0-99.1 sec 3847 MBytes 326 Mbits/sec 0.068 ms 247494/3029365 (8.2%) --> I want 326
So in the first step i want the Number Mbits/sec
This is My code snippet
Regex TP_PatternInt = new Regex(@"(?<TP>\d+) Mbit/sec");
Match TP_MatchInt = TP_PatternInt.Match(StringName);
string ResultInt = TP_MatchInt.ToString().Split(' ')[0];
Regex TP_PatternFloat = new Regex(@"(?<TP>\d+).\d Mbit/sec");
Match TP_MatchFloat = TP_PatternFloat.Match(StringName);
string ResultFloat = TP_MatchFloat.ToString().Split(' ')[0];
if (TP_MatchFloat.Success) Return ResultFloat;
else if(TP_MatchInt.Success) return ResultInt;
but when I run it I never get TP_MatchFloat.Success == true
What am I missing here ? Can someone propose a single pattern for both cases ?
EDIT added the look of the input string to be more precise
Using positive lookahead, you can dispense with groups:
\d+(?:\.\d+)?(?= Mbit/sec)
So this will match both 66.6
in your first example and 329
in your second, but only if they are followed by Mbit/sec
.
I suggest removing the fractional part once you've extracted the value by parsing to decimal and using Math.Floor
.
var str = "329 Mbit/sec";
var regex = new Regex(@"^-?\d+(?:\d+)?(?= Mbit/sec)");
var match = regex.Match(str);
if (match.Success)
{
var value = decimal.Parse(match.Value, CultureInfo.InvariantCulture);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.