How to provide custom string placeholder for string format

后端 未结 8 2191
借酒劲吻你
借酒劲吻你 2020-12-24 07:15

I have a string

string str =\"Enter {0} patient name\";

I am using string.format to format it.

String.Format(str, \"Hello\         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 07:27

    Regex with a MatchEvaluator seems a good option:

    static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled);
    static void Main()
    {
        string input = "this {foo} is now {bar}.";
        StringDictionary fields = new StringDictionary();
        fields.Add("foo", "code");
        fields.Add("bar", "working");
    
        string output = re.Replace(input, delegate (Match match) {
            return fields[match.Groups[1].Value];
        });
        Console.WriteLine(output); // "this code is now working."
    }
    

提交回复
热议问题