【发布时间】:2014-01-07 13:45:13
【问题描述】:
我有一个文本文件,我必须读取文本文件,然后将文件数据转换为表格形式。 文件就是这种形式
{KeyValuePair}
{
Key1 = Value1 {next}
Key2 = Value2 {next}
Key3 = Value3 {next}
Key4 = {KeyValuePair} {
KeyA = ValueA {next}
KeyB = ValueB {next}
KeyC = ValueC {next}
}
}
我需要这样的输出
我的逻辑代码在这里
StreamReader reader = new StreamReader("C:\\Users\\Kaushik Kishore\\Documents\\TextToRead.txt");
string data = reader.ReadToEnd();
//string[] stringSeparater = new string[] { "{KeyValuePair}" };
//string[] getData = data.Split(stringSeparater, StringSplitOptions.None);
//string[] separater = new string[] { "{next}" };
//string[] nextSplit = data.Split(separater, StringSplitOptions.None);
string pattern = @"(=)|(next)|(KeyValuePair)|({)|(})";
string[] output = Regex.Split(data, pattern);
foreach (string one in output)
{
Response.Write(one);
}
所以我面临的问题是如何编写实际的逻辑来提取所需的字符串。 Next 指定我们必须更改表中的行。每次出现下一个关键字时,我都必须在新行中发布数据。 提前致谢
编辑 我做了一些努力并写了一些代码 这是打印数据现在我想知道如何将数据从控制器传递到视图。当数据进入循环部分时。
public ActionResult Index()
{
StreamReader reader = new StreamReader("C:\\Users\\Kaushik Kishore\\Documents\\Text2.txt");
string data = reader.ReadToEnd();
// replacing all tabs white space new line and everything
string trimmedData = Regex.Replace(data, @"\s", "");
string pattern = @"({next})|({KeyValuePair}{)|(}{next})";
string[] output = Regex.Split(trimmedData, pattern);
int length = output.Length;
int count = 0;
foreach (string one in output)
{
count++;
if (one == "{KeyValuePair}{")
{
Response.Write("Table Create</br>");
}
else if (count == length)
{
string[] last = one.Split('=');
foreach (string lastVal in last)
{
Response.Write(lastVal.Substring(0,lastVal.Length-1));
Response.Write('|');
}
}
else
{
string[] keyVal = one.Split('=');
foreach (string val in keyVal)
{
if (val == "{next}")
{
Response.Write("</br>");
}
else if (val == "}{next}")
{
Response.Write("Subtable End</br>");
}
else if (val == "}")
{
Response.Write("");
}
else
{
Response.Write(val);
Response.Write("|");
}
}
}
}
reader.Close();
return View();
}
【问题讨论】:
-
@SamLeach 我已经提到了文本文件格式。以上请通过。