Skip to content

Instantly share code, notes, and snippets.

@alextercete
Created May 10, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alextercete/87efaa847a48b204f04894c420a5de15 to your computer and use it in GitHub Desktop.
Save alextercete/87efaa847a48b204f04894c420a5de15 to your computer and use it in GitHub Desktop.

Dictionary replacer

Problem

See: http://codingdojo.org/kata/DictionaryReplacer/

Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

internal class Program
{
  public static void Main(string[] args)
  {
    var input = "My name is $name$ $surname$ and I'm $age$ years old. $bio$";
    var values = new Dictionary<string, string>() {
      {"name", "John"},
      {"surname", "Doe"},
      {"age", "42"}
    };

    Console.WriteLine(DictionaryReplacer.Replace(input, values));
    // Output: My name is John Doe and I'm 42 years old.
  }
}

internal static class DictionaryReplacer
{
  public static string Replace(string input, IDictionary<string, string> values)
  {
    return Regex.Replace(input, @"\$(\w+)\$", match => {
      var key = match.Groups[1].Value;
      return values.ContainsKey(key) ? values[key] : string.Empty;
    });
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment