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

442 views Asked by At

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?

2

There are 2 answers

0
Shahar Shokrani On BEST ANSWER

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);
}            
0
Sherif Elmetainy On

You can use regular expression as follows:

var regex = new Regex("\\[([^\\]]+)\\]");
var match = regex.Match(readText);
if (match.Success)
{
    var value = match.Groups[1].Value;
    // value == "Information" or whatever between [ and ]
}
else
{
    // Handle pattern not matching
}