如何创建正则表达式以从日志文件中获取特定(bug.updateBug)字符串

时间:2013-05-09 04:28:27

标签: c# .net regex

如何创建正则表达式以从日志文件中可用的以下行获取特定(bug.updateBug)字符串,如下所示: WX编辑错误:3550704服务器:servername用户:testuser appGUID:appguidvalue经过时间:624ms方法:bug.updateBug日期:Wed May 01 09:38:01 PDT 2013

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

namespace ConsoleApplication59
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<string> textLines
                           = Directory.GetFiles(@"C:\testlocation\", "*.*")
                             .Select(filePath => File.ReadLines(filePath))
                             .SelectMany(line => line);

            List<string> users = new List<string>();
            Regex r = new Regex("^.*WX\\sADVSearch(.*)50\\]$");
            foreach (string Line in textLines)
            {
                if (r.IsMatch(Line))
                {
                    users.Add(Line);
                }
            }
            string[] textLines1 = new List<string>(users).ToArray();
            int countlines = textLines1.Count();
            Console.WriteLine("WX_ADVSearch=" + countlines);
            // keep screen from going away
            // when run from VS.NET
            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

似乎您的数据形式类似于键/值对。尝试使用此正则表达式:

(?<=method\:)([^ ]+)

下面:

方法是要查找其值的键。 除了下一个键之外的任何东西都应该是它的价值。

希望它有所帮助!

修改

        static void Main(string[] args)
        {
            IEnumerable<string> textLines = Directory.GetFiles(@"C:\testlocation\", "*.*")
                             .Select(filePath => File.ReadLines(filePath))
                             .SelectMany(line => line);

            //List<string> users = new List<string>();
            //Regex r = new Regex("^.*WX\\sADVSearch(.*)50\\]$");
            string text = String.Join("",textLines.ToArray());

            MatchCollection mcol = Regex.Matches(text,"(?<=method\:)([^ ]+)");
            //foreach (string Line in textLines)
            //{
            //    if (r.IsMatch(Line))
            //    {
            //        users.Add(Line);
            //    }
            //}
            //string[] textLines1 = new List<string>(users).ToArray();
            int countlines = mcol.Count; //textLines1.Count();
            Console.WriteLine("WX_ADVSearch=" + countlines);
            // keep screen from going away
            // when run from VS.NET
            Console.ReadLine();
        }