C# 如何通过分组解析文本文件?

标签 c# parsing text

我有一个简单的程序,它读取日志文本文件并尝试解析它。

该程序将能够通过“--------------------”来“分组”/解析日志文本文件,我曾尝试使用“.split”方法,但它不起作用。

基本上,如果可能的话,我希望程序将每个“----------------”到“------------”之间的文本文件分组----”用于其他进程。

有人可以就代码提供建议吗?谢谢!

我的代码:

class Program
{
    static void Main(string[] args)
    {

        System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("C:\\Syscrawl\\new.txt");

        foreach (String r in lines.Skip(7))
        {

            String[] token = r.Split('-');

            foreach (String t in token)
            {
                Console.WriteLine(t);
            }
        }
    }
}

文本文件示例;

Restore Point Info
Description   : Installed Apache HTTP Server 2.2.16
Type          : Application Install
Creation Time : Thu Dec  9 08:04:46 2010

C:\syscrawl\Restore\RP10\snapshot\_REGISTRY_USER_NTUSER_S-
1-5-21-1390067357-413027322-1801674531-500

Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs not found.
----------------------------------------
Restore Point Info
Description   : Testing 0
Type          : System CheckPoint
Creation Time : Thu Dec  9 08:05:43 2010

C:\syscrawl\Restore\RP11\snapshot\_REGISTRY_USER_NTUSER_S-
1-5-21-1390067357-413027322-1801674531-500

Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs not found.
----------------------------------------
Restore Point Info
Description   : Installed Python 2.4.1
Type          : Application Install
Creation Time : Thu Dec  9 08:09:12 2010

C:\syscrawl\Restore\RP12\snapshot\_REGISTRY_USER_NTUSER_S-
1-5-21-1390067357-413027322-1801674531-500

Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs not found.
----------------------------------------
Restore Point Info
Description   : Installed AccessData FTK Imager.
Type          : Application Install
Creation Time : Thu Dec  9 08:14:02 2010

C:\syscrawl\Restore\RP13\snapshot\_REGISTRY_USER_NTUSER_S-
1-5-21-1390067357-413027322-1801674531-500

Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs not found.

最佳答案

一个相当简单的迭代器可以为您提供分隔符之间的线集序列:

static IEnumerable<IList<string>> ParseLines(IEnumerable<string> lines)
{
    var lineSet = new List<string>();
    foreach(var line in lines)
    {
        if(line.StartsWith("----"))
        {
            yield return lineSet;
            lineSet = new List<string>();
        }
        else
        {
            lineSet.Add(line);
        }
    }
}

关于C# 如何通过分组解析文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4406243/

相关文章:

Python 过滤文本

div 内的 css 对齐列表

c# - 干这个方法

c# - 如何解决 "Service not available, closing transmission channel. The server response was: Server busy, too many connections"

c# - 从 C# 和 .NET 自动启动 java-web-start 应用程序,.WaitForExit();不按预期工作

linux - 在linux、bash中的单独列中回显2个变量

c - 从返回的消息中提取特定号码

c# - 验证错误阻止调用属性 setter

string - 解析字符串以查找可能引用的字段的通用 shell/bash 方法?

css - CSS 中的“文本边框”装饰