Reputation: 3879
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?
Upvotes: 1
Views: 454
Reputation: 8762
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);
}
Upvotes: 1
Reputation: 4502
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
}
Upvotes: 1