使用正则表达式读取日志文件

时间:2015-07-05 15:36:23

标签: c# regex

我需要将添加的文本读取到日志文件中并提取其中的一部分以保存在数据库中(编号> S3.20.140,开始扫描,scanId,scanTime,结果)。我需要阅读以下块:

[2015-06-23 13:45:01.768] .
[2015-06-23 13:45:01.768] Scan requested
[2015-06-23 13:45:01.768] random selection - S3.20.140 3 - 3
[2015-06-23 13:45:01.768] SV_ET_CMD_TYPE.SV_ET_CMD_SCAN: S3.20.140
[2015-06-23 13:45:01.784] Notification: Activity=SCAN_STARTED ScanId=14
[2015-06-23 13:45:07.884] SCUMsgClient: to receive 235 rectangles
[2015-06-23 13:45:07.884] Total scan 14 time: - 6.1 sec
[2015-06-23 13:45:07.915] HIP detection result is "OBJECTS DETECTED"
[2015-06-23 13:45:07.915] Scan results are ready.
[2015-06-23 13:45:11.128] User cleared scan 14
[2015-06-23 13:45:11.128] .

此块对于每次扫描都是相同的,但日志文件中还有其他我不想处理的信息。对此最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            string inputLine = "";
            string pattern1 = @"^\[(?'datetime'[^\]]*)\](?'message'[^$]*)";
            Regex expr = new Regex(pattern1, RegexOptions.Multiline);
            while ((inputLine = reader.ReadLine()) != null)
            {
                inputLine = inputLine.Trim();
                Match match = expr.Match(inputLine);
                string x = match.Groups["datetime"].Value;
                DateTime date = DateTime.Parse(match.Groups["datetime"].Value);
                string message = match.Groups["message"].Value;
                if (message.Contains(":"))
                {
                    string[] array = message.Split(new char[] { ':' });
                    switch (array[0].Trim())
                    {
                        case "SV_ET_CMD_TYPE.SV_ET_CMD_SCAN" :
                            Console.WriteLine("Number : {0}", array[1].Trim());
                            break;
                    }
                }

            }
            Console.ReadLine();

        }
    }
}
​