使用regex读取日志文件
本文关键字:文件 日志 读取 regex 使用 | 更新日期: 2023-09-27 18:01:03
我需要读取日志文件中添加的文本,并提取其中的一部分保存在数据库中(编号>S3.20.140,开始扫描,scanId,scanTime,result(。我需要阅读以下区块:
[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] .
这个块对于每次扫描都是一样的,但日志文件中还有其他信息我不想处理。对此,最好的方法是什么?
试试这样的
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();
}
}
}