您的位置:首页 > 编程语言 > ASP

asp.net正则表达式提取网址、标题、图片等

2011-04-19 09:05 686 查看
asp.net正则表达式提取网页网址、标题、图片实例以及过滤所有HTML标签实例(1)
2011-01-21 21:11
无论你用什么语言,正则表达式的处理方法都是非常灵活、高效的,尤其是对某些字符串的抓取、过滤方面,更显其优势。

1、asp.net正则表达式提取网址、标题、图片等

例如,有如下的字符串:

<li><a href="http://www.webkaka.com/blog/archives/how-to-add-links-on-baidu-blog.html" title="怎样在百度空间添加友情链接"><span class="article-date">[14/11]</span>怎样在百度空间添加友情链接</a></li>

现在,需要提取 href 后面的网址,[]内的日期,和 链接的文字。

asp.net的实现方式如下:

string strHTML = "<li><a href=/http://www.webkaka.com/blog/archives/how-to-add-links-on-baidu-blog.html/ title=/"怎样在百度空间添加友情链接/"><span class=/"article-date/">[14/11]</span>怎样在百度空间添加友情链接</a></li>";

string pattern = "http://([^//s]+)/".+?span.+?//[(.+?)//].+?>(.+?)<";
Regex reg = new Regex( pattern, RegexOptions.IgnoreCase );

MatchCollection mc = reg.Matches( strHTML );
if (mc.Count > 0)
{
foreach (Match m in mc)
{
Console.WriteLine( m.Groups[1].Value );
Console.WriteLine( m.Groups[2].Value );
Console.WriteLine( m.Groups[3].Value );
}
}

2、asp.net正则表达式删除HTML代码

public static string NoHTML(string Htmlstring) //替换HTML标记
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([/r/n])[/s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "/"", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "/xa1", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "/xa2", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "/xa3", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "/xa9", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&#(/d+);", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<img[^>]*>;", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring.Replace(">", "");
Htmlstring.Replace("/r/n", "");
Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
return Htmlstring;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: