C# 解析此表的最简单方法是什么:

C# 解析此表的最简单方法是什么:,c#,winforms,C#,Winforms,我有要在表单中显示的列表。但首先,我想移动所有不相关的部分。这是我的清单: =================================================================== Protocol Hierarchy Statistics Filter: eth frames:8753 bytes:6185473 ip

我有要在表单中显示的列表。但首先,我想移动所有不相关的部分。这是我的清单:

===================================================================
Protocol Hierarchy Statistics
Filter:

eth                                      frames:8753 bytes:6185473
  ip                                     frames:8753 bytes:6185473
    tcp                                  frames:8661 bytes:6166313
      http                               frames:1230 bytes:792126
        data-text-lines                  frames:114 bytes:82636
          tcp.segments                   frames:56 bytes:41270
        image-gif                        frames:174 bytes:109968
          tcp.segments                   frames:57 bytes:37479
        image-jfif                       frames:195 bytes:154407
          tcp.segments                   frames:185 bytes:142340
        png                              frames:35 bytes:30521
          tcp.segments                   frames:20 bytes:15770
        media                            frames:39 bytes:32514
          tcp.segments                   frames:32 bytes:24755
        tcp.segments                     frames:6 bytes:1801
        xml                              frames:5 bytes:3061
          tcp.segments                   frames:1 bytes:960
      ssl                                frames:20 bytes:14610
    udp                                  frames:92 bytes:19160
      dns                                frames:92 bytes:19160
===================================================================

我想显示第一列(协议类型),在第二列中仅显示“frames:”后面的部分,不带字节:xxxx

可能使用Regex,大致如下:

Regex rgx = new Regex(@"^(?<protocol>[ a-zA-Z0-9\-\.]*)frames:(?<frameCount>[0-9]).*$");   
   foreach (Match match in rgx.Matches(myListOfProtocolsAsAString))
   {
      if(match.Success)
      {
         string protocol = match.Groups[1].Value;
         int byteCount = Int32.Parse(match.Groups[2].Value);
      }
   }
Regex rgx=新的Regex(@“^(?[a-zA-Z0-9\-\.]*)框架:(?[0-9]).*$”;
foreach(在rgx.Matches中匹配(mylistofprotocolsastring))
{
如果(匹配成功)
{
字符串协议=匹配。组[1]。值;
int byteCount=Int32.Parse(match.Groups[2].Value);
}
}

然后,您可以访问Match实例上的匹配组(协议和帧计数)。

使用曾经流行的Linq to对象

var lines = new string[]
  {
    "eth                                    frames:8753 bytes:6185473",
    "ip                                     frames:8753 bytes:6185473"
  };

var values = lines.Select(
    line=>line.Split(new string[]{"frames:", "bytes:"}, StringSplitOptions.None))
    .Select (items => new {Name=items[0].Trim(), Value=items[1].Trim()});

我在foreach命令中收到错误:“无法通过引用转换、装箱转换、取消装箱转换、换行转换或空类型转换将“System.Collections.Generic.List”类型转换为“string”@user979033:我想我已经更新了我的答案了?该字符串或MyListofprotocolsaString都是列表而不是字符串。如果是这样,那么使用StringBuilder将它们全部组合起来,或者对每个字符串多次运行Regex rgx.Match,而不是使用笨重的方式。