去除html中的javascript代码和其他标签

2007年06月18日 | 3,475 次浏览 | 标签: , | 1条评论  

昨天憋了一下午也没搞定,今天早上终于解决了多行匹配的问题。

protected static string parseHtml(string html)
{
string clearScriptPattern = @"]*>(.|n)*?";//前面去掉空格,中间(.|n)*?为非贪婪匹配
string clearStylePattern = @"(.|n)*?";
string clearHtmlPattern = @"<[^>]*>";
string clearSpacePattern = @" |&nbsp|s";
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;

string parseResult = Regex.Replace(html, clearScriptPattern, "", options);
parseResult = Regex.Replace(parseResult, clearStylePattern, "", options);
parseResult = Regex.Replace(parseResult, clearHtmlPattern, "", options);
parseResult = Regex.Replace(parseResult, clearSpacePattern, " ", options);
return parseResult;
}

推荐一个代码重构的工具Refactor!™ Pro,如果想自己的代码写得漂亮一点,用它没错。

评论(1)

  1. me 发表于2007年11月22日 9:52 am

    另外一个例子
    #region 过滤掉 html代码
    public static string StripHTML(string strHtml)
    {
    string [] aryReg ={
    @”]*?>.*?”,

    @”",
    @”([\r\n])[\s]+”,
    @”&(quot|#34);”,
    @”&(amp|#38);”,
    @”&(lt|#60);”,
    @”&(gt|#62);”,
    @”&(nbsp|#160);”,
    @”&(iexcl|#161);”,
    @”&(cent|#162);”,
    @”&(pound|#163);”,
    @”&(copy|#169);”,
    @”&#(\d+);”,
    @”–>”,
    @”",
    ” “,
    “\xa1″,//chr(161),
    “\xa2″,//chr(162),
    “\xa3″,//chr(163),
    “\xa9″,//chr(169),
    “”,
    “\r\n”,
    “”
    };

    string newReg =aryReg[0];
    string strOutput=strHtml;
    for(int i = 0;i”,”");
    strOutput.Replace(“\r\n”,”");
    return strOutput;
    }
    #endregion

发表评论

最受欢迎

评论最多