2012-04-02 82 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()}); 
相關問題