所以我有Text
文件我读过,在这个文件中我有这样的表:
My data Statistics:
=============================================================
Bla bla : 120
Bla bla bla bla : 1
Number of files : 1
Size : 1
Total : 1
这个表在Text
内多次出现,我这样读了这个表:
StreamReader reader...
string text = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(text, "My data Statistics:");
现在我想将Last表放在文件中:
int count = matches.Count;
Match match = matches[count - 1];
从这里我需要你的帮助:
根据字符串和值读取表并解析表的最佳方法是什么,例如:
第一行中的字符串为Bla bla
,值为120
答案 0 :(得分:1)
我创建了一个简单的演示程序来解释如何执行此操作的可能性。首先,我认为您的演示代码中存在一些错误。 当你说,你需要找到文本中的最后一个表。我不明白你如何使用正则表达式找到这个位置。
我试图通过评论解释代码。 玩得开心。
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
// Text as member here
private static readonly string Text = "My data Statistics:\n" +
"=============================================================\n" +
"Bla bla : 120\n" +
"Bla bla bla bla : 1\n" +
"Number of files : 1\n" +
"Size : 1\n" +
"Total : 1\n" + "\n";
// Define how to now when a table starts and when it ends
// Table starts when line is "My data Statistics:"
private static readonly string TableStartMarker = "My data Statistics:";
// Table ends when line is empty??? Not specified in question
private static readonly string TableEndMarker = "";
public static void Main()
{
// Split text by \n to get lines
var lines = new List<string>(Text.Split('\n'));
// Find last line where content is the TableStartMarker (My data statistics...
var lastTableStart = lines.FindLastIndex(x => x == TableStartMarker);
//Iterate over all lines starting from last table header
foreach (var line in lines.Skip(lastTableStart))
{
// if line is empty -> table has endend
if (line == TableEndMarker)
return;
//now we have content -> split by :
var split = line.Split(':');
if (split.Length < 2)
continue;
//remove whitespaces and there you go: key and value
var key = split[0].TrimEnd();
var value = split[1].TrimStart();
Console.WriteLine(string.Format("Key: {0}, Value: {1}", key, value));
}
}
}