使用正则表达式从 C# 中的文本文件中获取开始值和结束值

本文关键字:获取 结束 开始 文件 正则表达式 文本 | 更新日期: 2023-09-27 17:57:06

我正在尝试编写一个从.txt文件中读取文本的 c# 程序。除了从文件中读取外,我还希望它从文本文件中的特定区域读取,以便使用正则表达式声明开始和结束位置。例如,我的文本文件可能包含以下短语:

"秒和服务器时间戳为'1468315683'秒完成预句柄"

我可能想读取服务器完成之间的值

我正在尝试使用以下代码实现此目的,程序运行成功但不记录值。

        string text;
        StreamReader file = new StreamReader(@"C:'FOLDER'FILE.txt");
        while((text = file.ReadToEnd()) != null)
        {
            if(text.Contains("server") )
            {
                var regex = new Regex(@"(?<='server ).*?(?='Finished)");
                foreach (Match match in regex.Matches(text))
                Console.WriteLine(match.Value);
                Console.ReadKey();
            }
       }

使用正则表达式从 C# 中的文本文件中获取开始值和结束值

我建议你按如下方式修复你的代码:

string text;
using (var file = new StreamReader(@"C:'FOLDER'FILE.txt")) 
{
    text = file.ReadToEnd();
    if (text.Contains("server") )
    {
        foreach (Match match in Regex.Matches(text, @"(?s)server(.*?)Finished"))
            Console.WriteLine(match.Groups[1].Value);
        Console.ReadKey();
    }
}

目标点:

  • 读取/写入文件时使用using,以便在完成后自动释放对象
  • 正则表达式应该知道.通过添加 DOTALL 修饰符来匹配任何符号(?s)
  • 捕获
  • 组方法比基于环顾的方法更有效,使用server(.*?)Finished捕获serverFinished之间的文本到Groups[1]中。

不要转义sF;另一个建议是使用 Linq 而不是阅读器:

var lines = File
  .ReadLines(@"C:'FOLDER'FILE.txt")
  .SelectMany(line => Regex
     .Matches(line, @"(?<=server's+).*?(?='s+Finished)")
     .OfType<Match>())
  .Select(match => match.Value);
// "timestamp is '1468315683' seconds" 
// for the one line file (the line has been taken from the question) 
foreach (string found in lines)
  Console.WriteLine(found);
Console.ReadKey();