2012-12-14 45 views
-1

我收到此表從我的過程輸出到List<string>解析字符串表

enter image description here

List<string> list = new List<string>(); 
StreamReader reader = tsharkProcess.StandardOutput; 

      while (!reader.EndOfStream) 
      { 
       string read = reader.ReadLine(); 
       list.Add(read); 
      } 

這將是解析此表只顯示IP地址的最佳方式,價值和血統?

+1

此選項卡分隔?如果是這樣,你可以分割'\ t'。 –

+3

你真的需要最好的方式或任何方式就夠了嗎? –

+0

我不認爲限制器是選項卡,我有什麼嘗試是3字典<字符串,雙>但它會是壞主意 – user1710944

回答

1

這如果行是製表符分隔

using(StreamReader reader = tsharkProcess.StandardOutput) 
{ 
    while (!reader.EndOfStream) 
    { 
     string[] values = reader.ReadLine().Split('\t'); 
     if (values.Length == 4) 
     { 
      string ipAddress = values[0]; 
      string value = values[1]; 
      string percentage = values[3]; 
      ... 
     } 
    } 
} 

如果沒有,那麼它可以使用正則表達式做會讀上飛的ip地址,值和百分比。

using(StreamReader reader = tsharkProcess.StandardOutput) 
{ 
    while (!reader.EndOfStream) 
    { 
     string row = reader.ReadLine(); 
     string[] values = Regex.Split(row, @"\s+", RegexOptions.None); 
     if (values.Length == 4) 
     { 
      string ipAddress = values[0]; 
      string value = values[1]; 
      string percentage = values[3]; 
      ... 
     } 
    } 
} 

和硬核regEx解決方案。

public class MyClass 
{ 
    // Lots of code.... 

    private static Regex regexRowExtract = new Regex(@"^\s*(?<ip>\d+\.\d+\.\d+\.\d+)\s*(?<value>\d+)\s+(?<rate>\d+\.?\d*)\s+(?<percentage>\d+\.?\d*)%\s*$", RegexOptions.Compiled); 

    public void ReadSharkData() 
    { 
     using(StreamReader reader = tsharkProcess.StandardOutput) 
     { 
      while (!reader.EndOfStream) 
      { 
       string row = reader.ReadLine(); 
       Match match = regexRowExtract.Match(row); 
       if (match.Success) 
       { 
        string ipAddress = match.Groups["ip"].Value; 
        string value = match.Groups["value"].Value; 
        string percentage = match.Groups["percentage"].Value; 

        // Processing the extracted data ... 
       } 
      } 
     } 
    } 
} 

對於正則表達式的解決方案,您應該使用:

using System.Text.RegularExpressions; 
+0

「\ s +」無法識別的轉義序列 – user1710944

+0

你應該使用@「\ s +」,抱歉遺忘@ – Casperah

+0

我需要以其他方式聲明行靜態正則表達式regexRowExtract(...)? (收到2個錯誤:1.預期;或=(不能在聲明中指定構造函數參數)2.修飾符'static'對此項無效) – user1710944

0

我會用正則表達式,也許不是最好的,但解決它的一種方法。

正則表達式IP

\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b 

我沒有檢索算法對於任何正則表達式%,但我認爲這不是會這麼難。

0

您可以創建一個正則表達式,它將匹配行中不同的值,並逐行解析文件。它應該是相對容易的,因爲所有的值都被空格分開。