0

I have written this very straight forward regex code

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            string lines = "2019-05-07 11:50:28, INFO Ayush Singhania, Level 1, EID: 1001, UID: ayush.power, Message: Create a Job";
            Regex pattern = new Regex(@"(?<Date>.*?\s)(?<Time>.*?), INFO(?<Name>.*?),(?<Level>.*?), EID: (?<EID>.*?), UID: (?<UID>.*?), Message: (?<Message>.*?)");

            MatchCollection myMatchCollection = pattern.Matches(lines);
            foreach (Match myMatch in myMatchCollection)
            {
                var Date = myMatch.Groups["Date"].Value;
                var Time = myMatch.Groups["Time"].Value;
                var Name = myMatch.Groups["Name"].Value;
                var Level = myMatch.Groups["Level"].Value;
                var EID = myMatch.Groups["EID"].Value;
                var UID = myMatch.Groups["UID"].Value;
                var Message = myMatch.Groups["Message"].Value;

                Console.Out.WriteLine(Date);
                Console.Out.WriteLine(Time);
                Console.Out.WriteLine(Name);
                Console.Out.WriteLine(Level);
                Console.Out.WriteLine(EID);
                Console.Out.WriteLine(UID);
                Console.Out.WriteLine(Message);
            }
        }
    }
}

The Output for the following is:

2019-05-07
11:50:28
Ayush Singhania
Level 1
1001
ayush.power
........... (The Last Line is Blank)

Everything is working fine excel for the last group - "Message"
It does not print anything. Can anyone suggest why is it so?
Also i think my regex pattern is correct. Check it here https://regex101.com/r/ysawNT/1

  • Look at the regex for the last group (MSG): `.*?` Do you know what it actually does? (Learn/explain what the dot `.` does, learn/explain what the asterisk `*` does, and learn/explain what the question mark `?` there does) –  May 08 '19 at 16:30
  • Remove the `?` from your MSG group so it is now: `(?.*)` and call `MSG` instead of `Message` when grabbing the value – dvo May 08 '19 at 16:30
  • The `MSG` was a mistake. I edited the original post. The name of the title was not the issue. It was the last `?` at the end. – Ayush Singhania May 08 '19 at 16:37

2 Answers2

3

Apart from using the wrong message Groups["Message"] which should be MSG, the last part is empty because the last part has no boundary set and the non greedy .*? is also satisfied to match nothing.

What you could do is match the rest of the string using (?<MSG>.*)

Regex demo | C# demo

enter image description here

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    `MSG` was a mistake, i copied it here too. I edited the post. The problem was with `?` at the end. Removed it. Worked like a Charm!! Thanks – Ayush Singhania May 08 '19 at 16:39
1

Your group should be MSG

var Message = myMatch.Groups["MSG"].Value;
andyb952
  • 1,931
  • 11
  • 25