替换字符串

时间:2016-02-24 06:43:24

标签: c# .net

我有一个带占位符的字符串,我想用值替换占位符。但问题是占位符本身包含多个占位符。

例如

string s = "My name is {Name}";

现在,我想替换{Name},但{Name}包含以下占位符

  1. {名字} {姓氏}
  2. {名字}
  3. {姓氏}
  4. 我想随机选择一个占位符并替换为{Name}。

    最后我想要以下输出

    My name is ABC

    My name is ABC XYZ

    My name is XYZ

2 个答案:

答案 0 :(得分:0)

您可以使用一些方法来解决此问题

正则表达式

string s = "My name is {Name}";
string result= Regex.Replace(s, "{name}", "ABC");

格式

string name="ABC";
string result= string.Format("My name is {0}", name);

插值表达式

string name="ABC";
string result= $"My name is {name}";

答案 1 :(得分:0)

你在这里:

using System.Text.RegularExpressions;


static void Main()
{
    string s = "My name is {Name} - {Gender}";

    Dictionary<string, List<string>> placeHolders = new Dictionary<string, List<string>>
    {
        {"Name", new List<string>{"FIRST", "LAST"}},
        {"Gender", new List<string>{"Male", "Female"}}
    };
    foreach(var item in placeHolders)
    {
        if (item.Value.Count == 2) item.Value.Add(string.Join(" ", item.Value));
    }
    var sSplit = Regex.Split(s, "(\\{[a-zA-Z]*\\})");
    List<string> results = new List<string> { "" };
    foreach (var item in sSplit)
    {
        Match m = Regex.Match(item, "{([a-zA-Z]*)}");
        if (!m.Success)
        {
            for (int i = 0; i < results.Count; i++) results[i] += item;
        }
        else
        {
            if (placeHolders.ContainsKey(m.Groups[1].Value))
            {
                List<string> tempList = new List<string>();
                foreach (var r in results)
                {
                    foreach (var p in placeHolders[m.Groups[1].Value]) tempList.Add(r + p);
                }
                results = tempList;
            }
        }
    }
    foreach (var str in results)
        Console.WriteLine(str);
    Console.ReadLine();
}

输出:

My name is FIRST - Male
My name is FIRST - Female
My name is FIRST - Male Female
My name is LAST - Male
My name is LAST - Female
My name is LAST - Male Female
My name is FIRST LAST - Male
My name is FIRST LAST - Female
My name is FIRST LAST - Male Female