替换特定字符之间的数据

本文关键字:数据 之间 字符 替换 | 更新日期: 2023-09-27 17:53:46

我有一个字符串,在<<>>之间有一些键

 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可以是任何东西,键的个数和它们的值也可以变化,但键总是包含在<<>>

替换特定字符之间的数据

根据@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());

这个函数将使用Regex执行您所要求的替换。替换:

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>你好约翰,& lt; br/祝辞你好doing

你可以在字典或名字列表的循环中调用它

您的业务逻辑有点不清楚,因此基于仅合格的猜测,您可以应用标准的。net/c# String.Replace方法(String, String)(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");

//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);