Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use a regex to match a balanced pair, then figure out what to do with the braces. Remember that .NET regexs aren't "regular".</p> <pre><code>class Program { static void Main(string[] args) { var d = new Dictionary&lt;string, string&gt; { { "Name", "World" } }; var t = new Test(); Console.WriteLine(t.Replace("Hello {Name}", d)); Console.WriteLine(t.Replace("Hello {{Name}}", d)); Console.WriteLine(t.Replace("Hello {{{Name}}}", d)); Console.WriteLine(t.Replace("Hello {{{{Name}}}}", d)); Console.ReadKey(); } } class Test { private Regex MatchNested = new Regex( @"\{ (?&gt; ([^{}]+) | \{ (?&lt;D&gt;) | \} (?&lt;-D&gt;) )* (?(D)(?!)) \}", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.Singleline); public string Replace(string input, Dictionary&lt;string, string&gt; vars) { Matcher matcher = new Matcher(vars); return MatchNested.Replace(input, matcher.Replace); } private class Matcher { private Dictionary&lt;string, string&gt; Vars; public Matcher(Dictionary&lt;string, string&gt; vars) { Vars = vars; } public string Replace(Match m) { string name = m.Groups[1].Value; int length = (m.Groups[0].Length - name.Length) / 2; string inner = (length % 2) == 0 ? name : Vars[name]; return MakeString(inner, length / 2); } private string MakeString(string inner, int braceCount) { StringBuilder sb = new StringBuilder(inner.Length + (braceCount * 2)); sb.Append('{', braceCount); sb.Append(inner); sb.Append('}', braceCount); return sb.ToString(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload