Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format with curly braces

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?

like image 943
lysergic-acid Avatar asked Nov 15 '11 08:11

lysergic-acid


1 Answers

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 {{ }}

like image 196
Anders Arpi Avatar answered Sep 23 '22 03:09

Anders Arpi