在項目中遇到這樣一個需求,需要將一段html轉換為一般文本返回,萬能的正則表達式來了。
正則表達式來拯救你,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public static string Html2Text( string htmlStr) { if (String.IsNullOrEmpty(htmlStr)) { return "" ; } string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>" ; //定義style的正則表達式 string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>" ; //定義script的正則表達式 string regEx_html = "<[^>]+>" ; //定義HTML標簽的正則表達式 htmlStr = Regex.Replace(htmlStr, regEx_style, "" ); //刪除css htmlStr = Regex.Replace(htmlStr, regEx_script, "" ); //刪除js htmlStr = Regex.Replace(htmlStr, regEx_html, "" ); //刪除html標記 htmlStr = Regex.Replace(htmlStr, "\\s*|\t|\r|\n" , "" ); //去除tab、空格、空行 htmlStr = htmlStr.Replace( " " , "" ); htmlStr = htmlStr.Replace( "" ", " ");//去除異常的引號" " " htmlStr = htmlStr.Replace( "" ", " "); return htmlStr.Trim(); } |
以上所述是小編給大家介紹的C#使用正則表達式過濾html標簽 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/ben121011/p/5778880.html?utm_source=tuicool&utm_medium=referral