2015-10-25 51 views
0

我正在嘗試編寫c#代碼來提取數據列。我的數據看起來像如何使用正則表達式提取數據列

enter image description here

應該是什麼正則表達式,如果我想提取在「列標題,例如「命令」或「PID」,「一切」」。

+0

只是分裂和抓住.. –

+0

但比我必須編寫的代碼行線bu線和拆分選項卡inst嗎? –

+0

看起來_column_具有空格,所以如果您希望列中有空格,則不能依賴_split_。可能最好的方法是使用已知的色譜柱長度(如果是固定的)或通過僅允許每個色譜柱的已知形式分離。 – sln

回答

0

不需要使用正則表達式。字符串拆分方法將起作用。嘗試這樣的代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Data; 


namespace ConsoleApplication53 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.txt"; 
     static void Main(string[] args) 
     { 
      DataTable dt = new DataTable(); 
      dt.Columns.Add("PID", typeof(int)); 
      dt.Columns.Add("TT", typeof(string)); 
      dt.Columns.Add("STAT", typeof(string)); 
      dt.Columns.Add("TIME", typeof(DateTime)); 
      dt.Columns.Add("COMMAND", typeof(string)); 

      StreamReader reader = new StreamReader(FILENAME); 
      int lineCount = 0; 
      string inputLine = ""; 

      while ((inputLine = reader.ReadLine) != null) 
      { 
       if (++lineCount > 2) 
       { 
        string[] inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 
        dt.Rows.Add(new object[] { 
         int.Parse(inputArray[0]), 
         inputArray[1], 
         inputArray[2], 
         DateTime.Parse(inputArray[3]), 
         inputArray[4] 
        }); 
       } 
      } 

     } 

    } 
} 
+0

我明白這一點。但這是一件試圖避免的事情。我在想,如果像正則表達式這樣的東西說給我的東西低於給定的字符串。 –

+0

該方法有什麼問題。爲什麼要避免正確解析文本數據。正則表達式給你的字符串數據,而不是日期和整數。並不會創建數組。上面的代碼給出了日期,整數和數組。 – jdweng