从文本文件中选择一行

时间:2014-12-01 11:34:48

标签: c# file parsing

我有一个包含以下行的文件

01/11/2009 23:23:23 ddd ttt,XYZ说你好

contains a paragraph of text which is not relevant

01/11/2009 23:23:23 ddd ttt,XYZ说早上

01/12/2009 21:21:21 ddd ttt,XYZ说你好吗

你最终的事情

你可以给我回电话吗?

contains a paragraph of text which is not relevant

01/12/2009 21:21:21 ddd ttt,XYZ说你好吗

这是我的问题, 我只使用StreamReader类读取包含日期,时间和关键字“Says”的那些行。在这样做时,提取了1行的所有聊天记录,但是具有多于1行的那些聊天记录被截断。 例如:01/12/2009 21:21:21 ddd ttt,XYZ说你怎么被提取但是句子

how are things at your end
Can you cal me back?

被截断了。 任何人都可以告诉我如何在不截断的情况下提取聊天记录的所有细节。

using (StreamReader sr = new StreamReader(path)) 
{
    while (File line = sr.readline())
    {
        if(line.contains("/") && line.contains(":") && line.contains("Says")
        {
            output the line to another file
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我尝试了以下内容:

  • 逐行阅读文件
  • 检测行的开始时间的时间戳,并创建一个新的 令牌。
  • 如果未找到时间戳,请将该行附加到上一个令牌。

结果是一个字符串列表,每个字符串包含一个会话令牌。

using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var tokens = new List<string>();
            foreach (string line in File.ReadAllLines("C:\\temp\\test.txt"))
            {
                if (Regex.IsMatch(line, @"^\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d"))
                {
                    tokens.Add(line);
                }
                else if(tokens.Count > 0)
                {
                    tokens[tokens.Count - 1] += "\r\n" + line;
                }
            }
        }
    }
}
相关问题