C# String replace with dictionary

If the data is tokenized (i.e. “Dear $name$, as of $date$ your balance is $amount$”), then a Regex can be useful:

static readonly Regex re = 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) {
            {"name", "Mr Smith"},
            {"date", "05 Aug 2009"},
            {"amount", "GBP200"}
        };
    string output = re.Replace(input, match => args[match.Groups[1].Value]);
}

However, without something like this, I expect that your Replace loop is probably about as much as you can do, without going to extreme lengths. If it isn’t tokenized, perhaps profile it; is the Replace actually a problem?

Leave a Comment