2017-03-17 51 views
0

我需要发送一个自定义的电子邮件消息给每个用户的列表(列表<用户>)我有。 (我正在使用C#.NET) 我需要做的是将所有表达式(以[[?& =“有”variableName“在中间,然后以”]“)结尾)用户属性值。用实际的类属性替换变量名 - Regex? (C#)

因此,举例来说,如果我有这样的文字:

"Hello, [?&=Name]. A gift will be sent to [?&=Address], [?&=Zipcode], [?&=Country]. 
If [?&=Email] is not your email address, please contact us." 

我想获得该用户:

"Hello, Mary. A gift will be sent to Boulevard Spain 918, 11300, Uruguay. 
If [email protected] is not your email address, please contact us." 

是否与要做到这一点实用,清洁的方式正则表达式?

+0

aplication的JavaScript,PHP或其他语言? – Scaffold

+0

@Scaffold我的坏,我没有指定(我编辑的问题)。我正在使用C# –

回答

0

这是应用正则表达式的好地方。

你想要的正则表达式看起来像这样/\[\?&=(\w*)\]/example

你需要做的使用方法,使您可以使用自定义函数替换值的输入字符串替换。然后在该函数中使用第一个捕获值作为Key以便说出并提取正确的对应值。

既然你没有指定你使用的是什么语言,我会很好,给你一个我最近为自己的项目制作的C#和JS的例子。

伪代码

Loop through matches 
Key is in first capture group 
Check if replacements dict/obj/db/... has value for the Key 
    if Yes, return Value 
    else return "" 

C#

email = Regex.Replace(email, @"\[\?&=(\w*)\]", 
       match => //match contains a Key & Replacements dict has value for that key 
        match?.Groups[1].Value != null 
        && replacements.ContainsKey(match.Groups[1].Value) 
         ? replacements[match.Groups[1].Value] 
         : ""); 

JS

var content = text.replace(/\[\?&=(\w*)\]/g, 
     function (match, p1) { 

      return replacements[p1] || ""; 

     });