C# 合并相同的日志并使用正则表达式添加计数

C# 合并相同的日志并使用正则表达式添加计数,c#,regex,C#,Regex,在C#中,我想使用正则表达式组合相同的行,并在行的末尾添加计数 这是我的日志文本: "000-00-0000" invalid ssn (1) "111-******" invalid ssn (1) "000-00-0000" invalid ssn (2) "55/22/2009" invalid date (1) "55/22/2009" invalid date (1) "55/22/2009" invalid date (3) 我想换成这个 "000-00-0000" invalid

在C#中,我想使用正则表达式组合相同的行,并在行的末尾添加计数

这是我的日志文本:

"000-00-0000" invalid ssn (1)
"111-******" invalid ssn (1)
"000-00-0000" invalid ssn (2)
"55/22/2009" invalid date (1)
"55/22/2009" invalid date (1)
"55/22/2009" invalid date (3)
我想换成这个

"000-00-0000" invalid ssn (3)
"111-******" invalid ssn (1)
"55/22/2009" invalid date (5)
我需要一个正则表达式模式来计算匹配项的数量,得到每个匹配项的数量并求和

在将每一行添加到日志之前,我使用以下代码

string error; // for example error = "000-00-0000" invalid ssn (1)
 if (log_errors.Contains(error)) // log_errors is my whole logs string
 {
 string pat = @"\b(" + error_string + " ([0-9]))" + @"\b";
 Match match = Regex.Match(log_errors, pat , RegexOptions.IgnoreCase);
  if (match.Success)
  {
   // Remove the line and add one to the same that already exist
  } 
 }

感谢您的帮助

如果行计数周围只有括号,您可以使用LINQ和split:

var newLog = (from log in log_errors
              let s = log.Split('(', ')')
              group s by s[0] into g
              select string.Concat(g.Key, "(", g.Sum(x => int.Parse(x[1])), ")"));
这将在新的字符串列表中存储所需内容。(我根据您的示例数据运行了它。)


可以用正则表达式描述行日志结构,并逐行解析:

var result = 
  log_errors.Select(line => Regex.Match(line, @"("".*"")(.*)\((\d+)\)").Groups)
            .Select(gc => new 
             {
                Id = gc[1].Value, 
                Text = gc[2].Value,
                Count = int.Parse(gc[3].Value)
             })
            .GroupBy(x => x.Id + x.Text, 
                    (k,v) => string.Format("{0} ({1})", k, v.Select(i => i.Count).Sum()))
            .ToList();
var result = 
  log_errors.Select(line => Regex.Match(line, @"("".*"")(.*)\((\d+)\)").Groups)
            .Select(gc => new 
             {
                Id = gc[1].Value, 
                Text = gc[2].Value,
                Count = int.Parse(gc[3].Value)
             })
            .GroupBy(x => x.Id + x.Text, 
                    (k,v) => string.Format("{0} ({1})", k, v.Select(i => i.Count).Sum()))
            .ToList();