2017-03-17 31 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] || ""; 

     });