2014-02-12 23 views
0

我有幾個文本文件應該是製表符分隔的,但實際上是由任意數量的空格分隔的。我想將文本文件中的行解析爲DataTable(文本文件的第一行包含屬性名稱的標題)。這讓我想到了構建一個可擴展,簡單的解析文本文件的方法。這裏是我當前工作的解決方案:使用Lambda表達式的正則表達式

string filePath = @"C:\path\lowbirthweight.txt"; 
      //regex to remove multiple spaces 
      Regex regex = new Regex(@"[ ]{2,}", RegexOptions.Compiled); 
      DataTable table = new DataTable(); 
      var reader = ReadTextFile(filePath); 
      //headers in first row 
      var headers = reader.First(); 
      //skip headers for data 
      var data = reader.Skip(1).ToArray(); 
      //remove arbitrary spacing between column headers and table data 
      headers = regex.Replace(headers, @" "); 
      for (int i = 0; i < data.Length; i++) 
      { 
       data[i] = regex.Replace(data[i], @" "); 
      } 
      //make ready the DataTable, split resultant space-delimited string into array for column names 
      foreach (string columnName in headers.Split(' ')) 
      { 
       table.Columns.Add(new DataColumn() { ColumnName = columnName }); 
      } 
      foreach (var record in data) 
      { 
       //split into array for row values 
       table.Rows.Add(record.Split(' ')); 
      } 
      //test prints correctly to the console 
      Console.WriteLine(table.Rows[0][2]); 
     } 
     static IEnumerable<string> ReadTextFile(string fileName) 
     { 
      using (var reader = new StreamReader(fileName)) 
      { 
       while (!reader.EndOfStream) 
       { 
        yield return reader.ReadLine(); 
       } 
      } 
     } 

在我的項目,我已經收到了不是在他們被自稱是格式幾個大的(演出+)的文本文件。所以我可以看到必須用一些規律來編寫這些方法,儘管使用了不同的正則表達式。有沒有辦法做類似 data =data.SmartRegex(x => x.AllowOneSpace)在哪裏我可以使用正則表達式遍歷字符串集合?

在正確的軌道上是如下的東西?

public static class SmartRegex 
    { 
     public static Expression AllowOneSpace(this List<string> data) 
     { 
      //no idea how to return an expression from a method 
     } 
    } 

我不是太過分關注性能,只是希望看到這樣的事情是如何工作的

+0

此代碼看起來並不擴展*或*易。 – Magus

回答

2

您應該與您的數據源協商,找出爲什麼你的數據是壞的。

至於你正試圖實現API設計:

public class RegexCollection 
{ 
    private readonly Regex _allowOneSpace = new Regex(" "); 

    public Regex AllowOneSpace { get { return _allowOneSpace; } } 
} 

public static class RegexExtensions 
{ 
    public static IEnumerable<string[]> SmartRegex(
     this IEnumerable<string> collection, 
     Func<RegexCollection, Regex> selector 
    ) 
    { 
     var regexCollection = new RegexCollection(); 
     var regex = selector(regexCollection); 
     return collection.Select(l => regex.Split(l)); 
    } 
} 

用法:

var items = new List<string> { "Hello world", "Goodbye world" }; 

var results = items.SmartRegex(x => x.AllowOneSpace); 
+0

我知道爲什麼數據源不好,不幸的是,這不是可以修復的東西:) – wootscootinboogie

+0

你能解釋這段代碼嗎?我不明白最後兩行代碼。 – wootscootinboogie

+0

最後兩行是哪一行? – Romoku

相關問題