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?


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


I think that you should look into your loggers interface. Compare with how Console.WriteLine works:

  • Console.WriteLine(String) outputs exactly the string given, no formatting, nothing special with { and }.
  • Console.WriteLine(String, Object[]) outputs using formatting. { and } are special characters that the caller must escape to {{ and }}
  • I think it's flawed design having to differentiate between different curly brace occurences in the code to find out what as meant. Lay the burden of escaping { that should occur in the output into {{.


    I would double all the curly braces and then I would look for those to be replaced with a regex like {{d+}} so that they came back to their original format -- {{0}} => {0} -- in your string.
    So for each line I would do sth like this

    string s = input.Replace("{", "{{").Replace("}", "}}");
    return Regex.Replace(s, @"{{(?<val>d+)}}", 
                         m => { return "{" + m.Groups["val"] + "}"; }));
    

    So that's a technical answer to the original question but @Anders Abel is perfectly right. It would be worth considering the design again...

    链接地址: http://www.djcxy.com/p/51478.html

    上一篇: 转义大括号{在一个字符串中支持String.Format

    下一篇: 带花括号的String.Format