简体   繁体   English

使用正则表达式并匹配以在字符串C#中查找模式

[英]using regex and match to find pattern in a string C#

I'm New in Regex programming and I want to search for a pattern example: 我是Regex编程的Regex ,我想搜索一个模式示例:

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 19:09:41 PM:[0] 0.0-100.2秒796 MBytes 66.6 Mbits / sec 0.273 ms 2454161/3029570(81%)->我要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 18:55:13 PM:[0] 0.0-99.1秒3847 MB​​ytes 326 Mbits / sec 0.068 ms 247494/3029365(8.2%)->我要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 但是当我运行它时我永远不会得到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 EDIT添加了输入字符串的外观,使其更加精确

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 . 因此,这将匹配第一个示例中的66.6和第二个示例中的329 ,但前提是它们后面跟随Mbit/sec

I suggest removing the fractional part once you've extracted the value by parsing to decimal and using Math.Floor . 我建议在解析Math.Floor小数并使用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);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM