我如何从文本文件中提取一大块文本?

问题描述 投票:0回答:1

我有一个后记文件,其中有一个开始指示符,指示我要开始将数据复制到读取以下内容的StringBuilder的位置:

$$StartCopy
$$ChunkID[1234]
$$Type[Foo]
\\bla bla for hundreds or thousands of lines
$$EndCopy  

$$StartCopy
$$ChunkID[4567]
$$Type[Bar]
\\bla bla for hundreds or thousands of lines
$$EndCopy 


$$StartCopy
$$ChunkID[4567]
$$Type[Foo]
\\bla bla for hundreds or thousands of lines
$$EndCopy

$$StartCopy
$$ChunkID[8901]
$$Type[Bar]
\\bla bla for hundreds or thousands of lines
$$EndCopy 

请注意,我没有可以开始的特定行,在$$ StartCopy和$$ EndCopy之间也没有任何设置的行数。在这种情况下,如何从$$Chunk[4567]的起始行到结束行截取$$Type[Bar]文本?

要清楚,这是最终结果应该是:

$$StartCopy
$$ChunkID[4567]
$$Type[Bar]
\\bla bla for hundreds or thousands of lines
$$EndCopy 
c# stringbuilder
1个回答
0
投票

由于您处理的是大文件和大量结果,因此最好使用File.ReadLines来返回File.ReadLinesIEnumerable<string>

iterator method

用法

/// <summary>
/// Will return the data from a file between the start and end parameters (inclusive)
/// </summary>
/// <param name="fileName">duh</param>
/// <param name="start">The start of the sequence</param>
/// <param name="end">The end of the sequence</param>
/// <returns>Stuff</returns>
public static IEnumerable<string> GetData(string fileName, string start, string end)
{
   var found = false;
   foreach (var line in File.ReadLines(fileName))
   {
      if (line == start) found = true;

      if (!found) continue;

      yield return line;

      if (line == end) break;
   }
}

[[[[[[Note):此代码未经测试,不会因您可能伤害或以其他方式伤害此代码的人而导致任何保修索赔,退货或退货。

var results = GetData(fileName, "$$StartCopy", "$$EndCopy"); 的出色评论

[Dai /ReadLine/ReadLineAsync方法是它们使用ReadLines字符串并且不让您手动指定

line-terminator

,使它们对于编写跨平台代码这就是说,此方法实际上仅处理以下情况,因为在确定实际line是什么时会固有地使用Environment.NewLine

对于非Unix平台,包含“ \ r \ n”的字符串,或字符串对于Unix平台,包含“ \ n”。

© www.soinside.com 2019 - 2024. All rights reserved.