Combine the same logs and add a regex counter

In C #, I want to use a regex to combine the same lines and add counters at the end of the line

this is my log text:

"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)

I want to replace this

"000-00-0000" invalid ssn (3)
"111-******" invalid ssn (1)
"55/22/2009" invalid date (5)

I need a regex pattern to count matches and get each one and sum them up

I use the following code before each line added to the log

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
  } 
 }

Thanks for any help

+3
source share
2 answers

If only parentheses are enclosed in the number of lines, you can use LINQ and split into them:

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])), ")"));

This will save what you want in a new list of strings. (I ran it against your sample data.)

"000-00-0000" invalid ssn (3)
"111-******" invalid ssn (1)
"55/22/2009" invalid date (5)
+4
source

:

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();
+1

All Articles