C# String replace with dictionary

前端 未结 8 2300
谎友^
谎友^ 2020-11-29 02:07

I have a string on which I need to do some replacements. I have a Dictionary where I have search-replace pairs defined. I have created fol

8条回答
  •  孤街浪徒
    2020-11-29 02:48

    when using Marc Gravell's RegEx solution, first check if a token is available using i.e. ContainsKey, this to prevent KeyNotFoundException errors :

    string output = re.Replace(zpl, match => { return args.ContainsKey(match.Groups[1].Value) ? arg[match.Groups[1].Value] : match.Value; });
    

    when using the following slightly modified sample code (1st parameter has different name):

        var args = new Dictionary(
            StringComparer.OrdinalIgnoreCase) 
            {
                {"nameWRONG", "Mr Smith"},
                {"date", "05 Aug 2009"},
                {"AMOUNT", "GBP200"}
            };
    

    this produces the following:

    "Dear $name$, as of 05 Aug 2009 your balance is GBP200"

提交回复
热议问题