2014-02-12 29 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

相关问题