Skip to content

Instantly share code, notes, and snippets.

@roundand
Last active August 29, 2015 13:57
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 roundand/9911397 to your computer and use it in GitHub Desktop.
Save roundand/9911397 to your computer and use it in GitHub Desktop.
linqPad demo of c# Regex extension method to replace tokens in a string using a token / value dictionary
<Query Kind="Program" />
// define regex to match $-delimited tokens, eg $name$
static Regex toke = new Regex(@"\$(\w+)\$", RegexOptions.Compiled);
static void Main()
{
string input = @"Dear $name$, as of $date$ your balance is $amount$";
var args = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
args.Add("name", "Mr Smith");
args.Add("date", "05 Aug 2009");
args.Add("amount", "£200");
string output = toke.replaceTokens(input, args);
output.Dump();
}
public static class ReplaceTokensUsingDictionary
{
public static string replaceTokens(this Regex re, string input, IDictionary<string, string> args)
{
return re.Replace(input, match => args[match.Groups[1].Value]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment