Our low level logging library has to cope with all sorts of log messages sent to it.
Some of these messages include curly braces (as part of the text), and some contain parameters to be formatted as part of the string using String.Format
For example, this string could be an input to the Logger class:
"Parameter: {Hostname} Value: {0}" With the correct variable sent to use for the formatter.
In order to properly do it, i must escape the curly braces that are not part of the formatting (by doubling them up).
I thought of doing it using Regex, however this is not as simple as it may seem, since i have no idea how to match these strings inside a curly braces (ones that are NOT used by String.Format for formatting purposes).
Another issue is that the Logger class should be as performance efficient as possible, starting to handle regular expressions as part of its operation may hinder performance.
Is there any proper and known best practice for this?
Doing it in just one regex:
string input = "Parameter: {Hostname} Value: {0}";
input = Regex.Replace(input, @"{([^[0-9]+)}", @"{{$1}}");
Console.WriteLine(input);
Outputs:
Parameter: {{Hostname}} Value: {0}
This of course only works as long as there aren't any parameters that contain numbers but should still be escaped with {{ }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With