2012-04-02 72 views
0

我有列表,我想要在我的窗体中显示。但首先,我想移动所有不相关的部分。这是我的清单:什么是解析此表最简单的方法:

=================================================================== 
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 
=================================================================== 

我想显示第一列(协议类型),并在第二列中只有部分经过“框:”无字节:XXXX

回答

1

可能使用正则表达式,东西沿的行:

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

然后就可以在匹配实例访问匹配组(协议&,帧数)。

+0

我的foreach命令接收到的错误:“无法通过引用转换转换型‘System.Collections.Generic.List ’到‘串’,装箱转换,拆箱转换,包装转换或空类型转换“ – user979033 2012-04-02 12:05:32

+0

@ user979033:我想我已经更新了我的答案?无论是或myListOfProtocolsAsAString是一个列表而不是一个字符串。如果是这样,那么使用StringBuilder将它们全部合并起来,或者对每个字符串运行多次rgx.Match的正则表达式,而不是笨重的方式。 – Ian 2012-04-02 12:54:04

1

使用日益流行的LINQ到对象

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()}); 
相关问题