替换C#中包含括号的字符串

本文关键字:字符串 包含括 替换 | 更新日期: 2024-09-20 23:59:35

我正试图用给定的变量替换C#电子邮件脚本中包含括号的字符串。函数中的一段代码如下:

MailDefinition md = new MailDefinition();
md.From = "testmail@test.com";    
string addressee = salutation;
ListDictionary replacements = new ListDictionary();
replacements.Add("'n", "<br />");
replacements.Add("(Name of Employee)", addressee)       
string body = EmployeeQuery.getEmailMessageByCategory(category, subcategory);
MailMessage msg = md.CreateMailMessage("admin@test.com", replacements, body, new System.Web.UI.Control());

主要问题是代码的这一部分:

replacements.Add("(Name of Employee)", addressee)    

"雇员姓名"替换为收件人变量的值。但是,它不会取代括号。

如何替换括号,以便只添加收件人的值?TIA

替换C#中包含括号的字符串

您需要放置"''''("answers"'''')"。@denims的答案可能部分正确,但c本身解释了字符串中的''。您可能需要''由您正在调用的方法进行解释。

也就是说,方法文档并没有说明为什么会发生这种情况。

使用此:

replacements.Add("''(Name of Employee'')", addressee)
// ' acts as escape charecter, supressing the special meaning of next charecter
// (XYZ) matches XYZ  as a group
// ''(XYZ'') matches (XYZ)