2011-10-17 189 views
2

如何剥离本文剥离HTML标签?

<html> 

<body>  

<h1>My First Heading</h1> 

<p>My first paragraph.</p> 
<[email protected]> 
</body> 
</html> 

看起来像

My First Heading 
My first paragraph. 
<[email protected]> 

使用功能

public static string StripHTML(this string htmlText) 
    { 
     var reg = new Regex("<(.|\n)*?>", RegexOptions.IgnoreCase); 
     return reg.Replace(htmlText, ""); 
    } 

我得到

我的第一个标题 我的第一个段落。

+3

<[email protected]>:它不会显示在html页面上。你应该htmlencode文本http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx或者你必须做一个非常具体的正则表达式来绕过<>标志中的电子邮件。 –

回答

2
static void Main(string[] args) 
    { 


     string modified_html = emas(input); 

     HtmlDocument doc = new HtmlDocument(); 

     doc.LoadHtml(modified_html); 

     string test1 = doc.DocumentNode.InnerText; 


     Console.WriteLine(); 


     var reg = new Regex("<(.|\n)*?>", RegexOptions.IgnoreCase); 

     Console.WriteLine(reg.Replace(modified_html , "")); 

     Console.Read(); 
    } 


    public static string emas(string text) 
    { 

     string stripped = text; 

     const string MatchEmailPattern = 
     @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" 
     + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." 
     + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" 
     + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})"; 
     Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); 
     // Find matches. 
     MatchCollection matches = rx.Matches(text); 
     // Report the number of matches found. 
     int noOfMatches = matches.Count; 
     // Report on each match. 
     foreach (Match match in matches) 
     { 

      stripped = stripped.Replace("<"+ match.Value + ">" , match.Value); 

     } 


     return stripped; 


    } 



    static string input = " Your html goes here "; 
+0

也许我会有

我的第一个标题

<[email protected]>我的第一段。

只有我希望HTML条功能不剥离电子邮件地址。 – cashmere

+0

我已经修改了代码 – Moons

+0

我已经修改了代码。您不能使用html敏捷包,因为它会去掉<>中包含的所有文本。这是我相信的。现在我搜索电子邮件地址并删除电子邮件附近的sysmbols < and >。请告诉你是否有任何问题 – Moons