我有几个文本文件应该是制表符分隔的,但实际上是由任意数量的空格分隔的。我想将文本文件中的行解析为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
}
}
我不是太过分关注性能,只是希望看到这样的事情是如何工作的
此代码看起来并不扩展*或*易。 – Magus