Search code examples
c#asp.net-corestringreaderstringwriter

Get parts of a string - C# .NET Core 3.1


I have a string line from a log:

2020-09-07 14:41:17.268 +01:00 [Information] Hello, Serilog!

I would like to pull out the word Information from the string, however, this will change as it could be debug, or any other known logging level.

I would also like the message, which is one space after the ] which in this case is Hello, Serilog!. This is also subject to change but it wont be any longer than the existing message.

The string is coming from a StringReader

 using (StringReader reader = new StringReader(message.ToString())) // message from StringWriter
{
    var readText = reader.ReadLine();
    Console.WriteLine(readText);
}

What is the best way to do this?


Solution

  • Using Regex will output Information: Hello, Serilog!

    string type;
    string message;
    
    string text = "2020-09-07 14:41:17.268 +01:00 [Information] Hello, Serilog!";
    string pattern = "\\[(.*?)\\]";
    var match = Regex.Match(text, pattern);
    if (match.Success)
    {
        type = match.Groups[1].Value;
        message = text.Substring(match.Groups[1].Index + match.Groups[1].Length + 1);
        Console.WriteLine(type + ": " + message);
    }