3

I want to parse a log file to retrieve the time, type and the message. A log file is constructed like this:

[08:52:18] [ERROR] Ceci doit aparaitre 
[08:52:18] [WARN] Bonjour 

I'm currently doing it like this:

var result = Regex.Match(fileLogs, @"/\[(.+)\] \[(.+)\] (.+)/g");

Which is working fine on website like RegexStorm but not on my code. I don't really understand why.

I want to retrieve these element to create a new instance of Log (which have just 3 attributes: time, type and message)

LoïcR
  • 4,940
  • 1
  • 34
  • 50
  • `but not on my code` => that's where we need more informations – Thomas Ayoub Mar 22 '16 at 09:43
  • 1
    What is `fileLogs`? Array of lines, a single line or what? – Nitro.de Mar 22 '16 at 09:45
  • fileLogs is just a string containing the example text above. Result is the whole line. – LoïcR Mar 22 '16 at 09:46
  • 1
    Okay then see xanatos answer. Be careful, if you want to read the whole Log-File at ones, you need to use `Regex.Matches` else you'll just get the first appearence – Nitro.de Mar 22 '16 at 09:47
  • for me `string fileLogs = "[08:52:18] [ERROR] Ceci doit aparaitre"; var result = Regex.Match(fileLogs, @"\[(.+)\] \[(.+)\] (.+)");` works just fine – Nitro.de Mar 22 '16 at 09:51

1 Answers1

4

Remove the initial / and the final /g. You are programming in C#, not Javascript.

var result = Regex.Match(fileLogs, @"\[(.+)\] \[(.+)\] (.+)");

Ideone showing that now it works: https://ideone.com/QkTYwS

To split it correctly you can use something like:

var result = Regex.Matches(fileLogs, @"\[(.+)\] \[(.+)\] (.+)");

foreach (Match match in result)
{
    string time = match.Groups[1].Value;
    string type = match.Groups[2].Value;
    string messsage = match.Groups[3].Value;
    Console.WriteLine("{0} | {1} | {2}", time, type, messsage);
}

Note the use of the Regex.Matches.

Ideone: https://ideone.com/lUxnSs

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Tried it too, but result.Value is the whole line. – LoïcR Mar 22 '16 at 09:46
  • @Sakuto *Which is working fine on website like RegexStorm but not on my code* Then it doesn't work fine with RegexStorm :-) – xanatos Mar 22 '16 at 09:48
  • Thanks, figured it out while you were writing it, thanks (: The /, /g was for testing purpose, it was not on my initial code but I had problem dealing with the Groups attribute. – LoïcR Mar 22 '16 at 09:54