Last active
August 29, 2015 13:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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