Although C # 6.0 can now do this with string interpolation, sometimes it needs to be done with dynamic format strings at runtime. I could not use other methods that require DataBinder.Eval due to the fact that they are not available in .NET Core, and were dissatisfied with the work of Regex solutions.
With that in mind, here I wrote a regular expression based analyzer. It handles unlimited levels {{{escaping}}} and throws a FormatException when an input contains unbalanced curly braces and / or other errors. Although the main method accepts a Dictionary<string, object> , the helper method can also take an object and use its parameters through reflection.
public static class StringExtension {
Ultimately, the whole logic comes down to 10 basic states: if the state machine is outside the bracket, and also inside the bracket, the next character is either an open curly bracket, an open bracket, a closed bracket, a closed bracket, or a regular character. Each of these conditions is processed individually during the cycle, adding characters to either the output value of the StringBuffer or the StringBuffer key. When the parameter is closed, the StringBuffer key value is used to find the parameter value in the dictionary, which is then inserted into the StringBuffer output.
EDIT:
I turned this into a complete project at https://github.com/crozone/FormatWith
Ryan Feb 23 '16 at 2:40 2016-02-23 02:40
source share