使用正则表达式和匹配来查找字符串中的模式C#

时间:2014-07-02 09:25:41

标签: c# regex

我是Regex编程的新手,我想搜索一个模式 例如:

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秒3847 MB​​ytes 326 Mbits / sec 0.068 ms 247494/3029365(8.2%) - >我想要326

所以在第一步中我想要数字 Mbits / sec

这是我的代码段

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;

但是当我运行它时,我永远不会得到TP_MatchFloat.Success == true

我在这里缺少什么? 有人可以为这两种情况提出单一模式吗?

编辑添加输入字符串的外观更精确

2 个答案:

答案 0 :(得分:1)

使用正向前瞻,您可以免除群组:

\d+(?:\.\d+)?(?= Mbit/sec)

因此,这与第一个示例中的66.6和第二个示例中的329相匹配,但前提是后跟Mbit/sec

我建议您在通过解析为十进制并使用Math.Floor提取值后删除小数部分。

答案 1 :(得分:0)

 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);
 }