0

以下两种情况均无效。我想从文本文件中提取可以通过指定行的开头和结尾来选择的某个部分。

  1. 案例如下所示:
using (StreamReader reader = new StreamReader("C:/Users/david/Desktop/20180820.log",Encoding.Default))
{
    Console.WriteLine("From:");
    string a = (Console.ReadLine());
    Console.WriteLine(" To:");
    string b = (Console.ReadLine());   
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if (line.StartsWith(a) && (line.EndsWith(b)))
        {
            Console.WriteLine(line);
        }
    }
}
  1. 正则表达式的情况
string line;
while ((line = reader.ReadLine()) != null)
{
    string regex12 = a.ToString() + b.ToString(); 
    Match m = Regex.Match(line,regex12);
    string s = Regex.Match(line, regex12).Groups[0].Value;
    Console.WriteLine(s);
    if (m.Success) 
    {
        string n = m.Groups[0].Value;
        Console.WriteLine(n);
    }
}

如果有人能解决我的问题,我将非常感激。

4

1 回答 1

0

根据评论更新

从评论来看,您似乎正在尝试解析特定格式的文件,并且使用非通用解决方案会更好地受益。此外,看起来文本被分成多行,而不是您在评论中共享的单行。

[00:09:08.870] text... 
[00:09:08.886] text... 
[00:09:08.886] text... 
[00:09:10.448] text... 
[00:09:10.464] text... 
[00:09:10.526] text... 
[00:09:11.886] text... 
[00:09:11.901] text... 
[00:09:11.980] text... 
[00:09:12.026] text...

在这种情况下,您可以使用以下内容。

var reader = File.OpenText(filePAth);
var startLineDetected = false;
var startWord = "00:09:08.870";
var endWord =  "00:09:12.026";
var strBuilder = new StringBuilder();
while(!reader.EndOfStream)
{
    var newLine = reader.ReadLine();
    if(newLine.Contains($"[{startWord}") && !startLineDetected)
    {
        startLineDetected = true;
    }

    if(newLine.Contains($"[{endWord}") && startLineDetected)
    {
        strBuilder.AppendLine(newLine);
        break;
    }

    if(startLineDetected)
    {
        strBuilder.AppendLine(newLine);
    }
}
var resultData = strBuilder.ToString();

基于OP的原始答案

您可以执行以下操作。

var reader = File.OpenText(filePAth);
var startLineDetected = false;
var startWord = // startWord;
var endWord =  // endWord;
var strBuilder = new StringBuilder();
while(!reader.EndOfStream)
{
    var newLine = reader.ReadLine();


    if(newLine.Contains(startWord) && !startLineDetected)
    {
        startLineDetected = true;
        newLine = newLine.Substring(newLine.IndexOf(startWord));
    }

    if(newLine.Contains(endWord) && startLineDetected)
    {
        newLine = newLine.Substring(0,newLine.IndexOf(endWord) + endWord.Length);
        strBuilder.Append(newLine);
        break;
    }


    if(startLineDetected)
    {
        strBuilder.Append(newLine);
    }
}
var resultData = strBuilder.ToString();
于 2019-11-30T12:24:17.303 回答