2013-05-06 67 views
0

使用MVC正則表達式模式,看看下面這個例子,我們有以下的HTML代碼:其中匹配的img標籤

<p>Duma</p><img url='..' /><p>Duma</p> 

我想是隻打印標籤的內容,如:

Duma [IMAGE] Duma 

卸下圖像(表示[IMAGE])標籤和僅示出文本(如的innerText)

我決定創建的擴展,其中,直到這一刻,僅示出了

Duma Duma 

public static class StringExtensions 
{ 
    public static string StripHtml (this string inputString) 
    { 
     return Regex.Replace 
     (inputString, "<.*?>", string.Empty); 
    } 
} 

我該怎麼做才能添加[IMAGE]每次正則表達式與img tags

+4

[RegEx match open tags but XHTML self-contained tags]可能的重複(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – 2013-05-06 17:53:43

回答

1

匹配你可以試試這個:

public static class StringExtensions 
{ 
    public static string StripHtml (this string inputString) 
    { 
     return Regex.Replace(
     Regex.Replace(inputString, "<img.*?>", "[IMAGE]"), "<.*?>", string.Empty); 
    } 
} 

它實際上調用了兩個Reges.Replace()一個其他內。 !st替換<img ...>標籤到[IMAGE],然後替換剩餘的字符串,只留下<p>標籤中的內容。