C#中的模式匹配

时间:2015-08-04 07:30:27

标签: c#

这是我的串口在文本框上接收数据。

Current consumed by device : 0.45
Power consumption: = [ 103.2277 ]
ENERGY CONSUMED: = [ 24.250 ]
Length = 6

Current consumed by device : 0.45
Power consumption: = [ 103.5094 ]
ENERGY CONSUMED: = [ 24.250 ]
Length = 4

我想只提取“耗电量”和“耗能量”的值,并且每次都通过串口显示在文本框中。

我如何有效地解析这个问题?

这是我的代码

enter code here

        Regex regex = new Regex(@"(Power consumption: (.*?) ])");
        Match match = regex.Match(temp);
        if (match.Success)
        {
            string abc = match.Value;
            string res = new string(abc.SkipWhile(c => c != '[')
                       .Skip(1)
                       .TakeWhile(c => c != ']')
                       .ToArray()).Trim();
            float f_num = float.Parse(res);
            //   trackBar1.Value = (int)f_num;

            textBox2.Text = f_num.ToString();

请建议我更快的代码。

1 个答案:

答案 0 :(得分:1)

您可能需要调整回车符/换行符,但这应该有效:

string text =
    "Current consumed by device : 0.45\r\nPower consumption: = [ 103.2277 ]\r\nENERGY CONSUMED: = [ 24.250 ]\r\nLength = 6\r\n\r\n"
    + "Current consumed by device : 0.45\r\nPower consumption: = [ 103.5094 ]\r\nENERGY CONSUMED: = [ 24.250 ]\r\nLength = 4\r\n";

Regex regex = new Regex(@"Power consumption:\s=\s\[\s(?<PowerConsumption>\d*.\d*)\s\]\r\nENERGY CONSUMED:\s=\s\[\s(?<EnergyConsumed>\d*.\d*)\s\]");

MatchCollection matches = regex.Matches(text);

foreach (Match match in matches)
{
    Console.WriteLine("Power Consumption: " + match.Groups["PowerConsumption"].Value);
    Console.WriteLine("Energy Consumed: " + match.Groups["EnergyConsumed"].Value);
}

给出:

  

耗电量:103.2277

     消耗的能量:24.250

     

耗电量:103.5094

     消耗的能量:24.250