Share via


C#: token replacement using regex

Here comes an easy way to replace tokens in a given string using plain C# regex's.

        static string ReplaceTokens(string template, Dictionary<string, string> replacements)
        {
            var rex = new Regex(@"\${([^}]+)}");
            return(rex.Replace(template, delegate(Match m)
            {
                string key = m.Groups[1].Value;
                string rep = replacements.ContainsKey(key)? replacements[key] : m.Value;
                return(rep);
            }));
        }

        static void Main(string[] args)
        {
            Dictionary<string, string> dict = new Dictionary<string,string>();
            dict.Add("username", "pepino");
            dict.Add("usermail", "pepe@yahoo.com");
            Console.WriteLine(ReplaceTokens("hi ${username}! I am ${username}. Email me to ${usermail}. And this token won't be replaced: ${unknown}.", dict));
        }

Above will output: "hi pepino! I am pepino. Email me to pepe@yahoo.com. And this token won't be replaced: ${unknown}."

Comments

  • Anonymous
    May 31, 2013
    60 times faster than string.replace and a very neat code