替换字符串中的嵌套占位符
本文关键字:嵌套 占位符 字符串 替换 | 更新日期: 2023-09-27 18:35:54
我有一个带占位符的字符串,我想用值替换占位符。但问题是占位符本身包含多个占位符。
例如。
string s = "My name is {Name}";
现在,我想替换{名称},但{名称}包含以下占位符
- {
- 名字} {姓氏}
- {名字}
- {姓氏}
我想随机选择一个 1 占位符并替换为 {Name}。
最后我想要以下输出
My name is ABC
或
My name is ABC XYZ
或
My name is XYZ
您可以使用一些方法来解决此问题
正则表达式
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}";
你在这里:
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