-2

我试图让我的代码过滤并从 txt 文件中的特定单词开始和结束。

是的,对不起。问题是,如何告诉它从一条线开始,在另一条线停止?

foreach (string line in File.ReadLines(@"C:\test.txt"))
{
  if (line.Contains("text"))
  {
    Console.WriteLine(line);
  }
}

我将详细说明我打算实现的目标。

它必须从“命令:更新”行开始并在最后停止。棘手的部分是,它必须从最后一个“命令:更新”开始。

Command              : Update
Updating             : C:\somepath\somepath\somefile1.doc
Completed            : C:\somepath\somepath\somefile1.exe
External             : C:\somepath\somepath\somefile1.fla
Completed            : C:\somepath\somepath\somefile1.txt
Completed            : C:\somepath\somepath\somefile1.doc
Completed            : C:\somepath\somepath\somefile1.exe
Command              : Update
Updating             : C:\somepath\somepath\somefile222.fla
External             : C:\somepath\somepath\somefile222.txt
Updating             : C:\somepath\somepath\somefile222.doc
Completed            : C:\somepath\somepath\somefile222.exe
External             : C:\somepath\somepath\somefile222.fla
Completed            : C:\somepath\somepath\somefile222.txt
Completed            : C:\somepath\somepath\somefile222.doc
Completed            : C:\somepath\somepath\somefile222.exe

首选输出是

C:\somepath\somepath\somefile222.doc
C:\somepath\somepath\somefile222.doc
4

1 回答 1

1

这不是最好的代码,可能会被清理一些,但这应该让你开始。此代码将读取行以查找指示开始写入的文本。然后它将输出行,直到找到指示已完成写入的文本。此时它将不再读取任何行并退出循环。

bool output = false;
foreach (var line in File.ReadLines("C:\\test.txt"))
{
    if (!output && line.Contains("beginText"))
    {
        output = true;
    }
    else if (output && line.Contains("endText"))
    {
        break;
    }

    if (output)
    {
        Console.WriteLine(line);
    }
}

根据问题更新进行编辑:

我将把结果行中的过滤留给你,因为我不确定定义应该输出什么和不应该输出什么的规则是什么,但这是一种至少在最后一个更新行之后获得结果的方法:

var regex = new Regex(@"Command\s+:\s+Update");
List<string> itemsToOutput = null;
foreach(var line in File.ReadLines("C:\\test.txt"))
{
    if (regex.IsMatch(line))
    {
        itemsToOutput = new List<string>();
        continue;
    }

    if (itemsToOutput != null)
    {
        itemsToOutput.Add(line);
    }
}
于 2012-12-19T08:58:32.337 回答