// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace E { public class Program { public static void Main(string[] args) { string s = "xxx [key1] yyy [key2] zzz"; string s2 = s.Replace("[key1]", "foo").Replace("[key2]", "bar"); Console.WriteLine(s2); string s3 = s; Regex re3 = new Regex(@"\[([^\]]*)\]"); foreach(Match m in re3.Matches(s)) { switch(m.Groups[1].Value) { case "key1": s3 = s3.Replace("[key1]", "foo"); break; case "key2": s3 = s3.Replace("[key2]", "bar"); break; } } Console.WriteLine(s3); Dictionary d = new Dictionary(); d.Add("key1", "foo"); d.Add("key2", "bar"); string s4 = s; Regex re4 = new Regex(@"\[([^\]]*)\]"); foreach(Match m in re4.Matches(s)) { s4 = s4.Replace("[" + m.Groups[1].Value + "]", d[m.Groups[1].Value]); } Console.WriteLine(s4); StringBuilder sb = new StringBuilder(); int ix = 0; while(ix < s.Length) { int newix = s.IndexOf("[key", ix); if(newix > 0) { sb.Append(s.Substring(ix, newix - ix)); string key = s.Substring(newix + 1, s.IndexOf("]", newix + 4) - newix - 1); sb.Append(d[key]); ix = newix + key.Length + 2; } else { sb.Append(s.Substring(ix)); ix = s.Length; } } string s5 = sb.ToString(); Console.WriteLine(s5); } } }