我有一个字符串,其中包含<<>>。
之间的一些键 string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>";
我想首先在列表中获取密钥名称USER和SENDER,我通过以下方式获取:
var keys = new List<string>();
foreach (Match match in Regex.Matches(s, @"<<(.*?)>>"))
{
keys.Add(match.Groups[1].Value);
}
List<string> values= new List<string>(){"John","Team"};
获取密钥后,我想用另一个列表(这里是命名值)替换这些密钥,这些列表具有这些密钥的值,并希望结果为:
string s = "<p>Hi John,<br/>How are you doing<br/>Regards,<br/>Team</p>";
字符串s
可以是任何内容,而密钥和它们的值也可以变化,但密钥将始终包含在&lt;&lt;&gt;&gt;
答案 0 :(得分:2)
此功能将使用Regex.Replace执行您要求的替换:
public static string ParseTemplate(string template, string username, string senderName)
{
template = Regex.Replace(template, @"<<USER>>", username);
return Regex.Replace(template, @"<<SENDER>>", senderName);
}
示例:
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>";
ParseTemplate(s, "John", "Team").Dump();
输出:
&lt; p&gt;嗨John,&lt; br /&gt;你好吗&lt; br /&gt;问候,&lt; br /&gt; Team&lt; / p&gt;
您可以在字典或名单列表中循环调用它。
答案 1 :(得分:2)
正如@AlexBell所建议的那样,您可以简单地使用String.Replace()
方法。
此外,声明占位符/值对的集合更方便,如下所示:
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>";
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("<<USER>>", "Jhon");
dictionary.Add("<<SENDER>>", "Team");
StringBuilder text = new StringBuilder(s);
foreach (var entry in dictionary)
{
text.Replace(entry.Key, entry.Value);
}
Console.WriteLine(text.ToString());
答案 2 :(得分:0)
您的业务逻辑有点不清楚,因此基于合格的猜测,您可以应用标准的.NET / C#String.Replace
方法(字符串,字符串)
(re:https://msdn.microsoft.com/en-us/library/fk49wtc1%28v=vs.110%29.aspx),例如:
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>".Replace("<USER>", "John").Replace("<SENDER>", "Team");
希望这可能会有所帮助。
答案 3 :(得分:0)
//First we have lists of values (users) and senders
List<string> values= new List<string>(){"John","Team"};
List<string> senders = new List<string>(){"John","Team"};
//Then we can join that list using string.join
var allUsers = string.Join(",", values);
var allSender = string.Join(",", senders);
//Next we will be replacing it in our string
var namedString = Regex.Replace(string, @"<<USER>>", allUsers);
var output = Regex.Replace(namedString , @"<<SENDER>>", allSender);