如何解決下面的問題?在C#ASP.NET中使用RegEx替換函數
我創建一個簡單的內容管理系統,那裏是一個HTML模板與特定的標記,它表示在內容應該是:
從這個<html><head></head><body><!-- #Editable "Body1" --><p>etc etc</p><!-- #Editable "Extra" --></body></html>
獨立,存在這樣看起來數據庫字段內容像這樣的小:
<!-- #BeginEditable "Body1" -->This is Test Text<!-- #EndEditable --><!-- #BeginEditable "Extra" -->This is more test text<!-- #EndEditable -->
正如您可以猜到,我需要合併兩個,那就是更換
<!-- #Editable "Body1" -->
有:
This is Test Text
我已經在這裏開始的代碼。但是我使用正則表達式替換功能,應設在對於/每最底部有問題....
//Html Template
string html = "<html><head></head><body><!-- #Editable \"Body1\" --><p>etc etc</p><!-- #Editable \"Extra\" --></body></html>";
//Regions that need to be put in the Html Template
string regions = "<!-- #BeginEditable \"Body1\" -->This is Test Text<!-- #EndEditable --><!-- #BeginEditable \"Extra\" -->This is more test text<!-- #EndEditable -->";
//Create a Regex to only extract what's between the 'Body' tag
Regex oRegex = new Regex("<body.*?>(.*?)</body>", RegexOptions.Multiline);
//Get only the 'Body' of the html template
string body = oRegex.Match(html).Groups[1].Value.ToString();
// Regex to find sections inside the 'Body' that need replacing with what's in the string 'regions'
Regex oRegex1 = new Regex("<!-- #Editable \"(.*?)\"[^>]*>",RegexOptions.Multiline);
MatchCollection matches = oRegex1.Matches(body);
// Locate section titles i.e. Body1, Extra
foreach (Match match in matches)
{
string title = oRegex1.Match(match.ToString()).Groups[1].ToString();
Regex oRegex2 = new Regex("<!-- #BeginEditable \"" + title + "\"[^>]*>(.*?)<!-- #EndEditable [^>]*>", RegexOptions.Multiline);
//
//
// Replace the 'Body' sections with whats in the 'regions' string cross referencing the titles i.e. Body1, Extra
//
//
//
}
完美,你讓我感到羞恥! – Stephen 2010-02-18 11:31:28
順便說一下,你應該提升'regionRegex'到私有靜態字段並追加'RegexOptions.Compiled'標誌,並使用'StringBuilder'在循環內進行替換。 – Diadistis 2010-02-18 11:37:40
感謝mill ...現場,我喜歡簡單。 – Stephen 2010-02-18 11:40:45