014天(.net学习之路

来源:互联网 发布:淘宝主播多少钱一个月 编辑:程序博客网 时间:2024/05/01 20:49

正则表达式2

练习1:抓取某网页上的图片
 1  static void Main(string[] args) 2         { 3             //下载某个网页的图片,下载到d:\1文件夹下 4             //例:抓取http://desk.zol.com.cn/首页的图片 5              6             WebClient wc = new WebClient(); 7             string content = wc.DownloadString("http://desk.zol.com.cn/"); 8             string reg = @"srch=""(?<url>.+?)"""; 9             //测试内容读取有没有乱码10             //Console.WriteLine(content);11             MatchCollection mc = Regex.Matches(content, reg);12             foreach (Match item in mc)13             {14                //打印下图片路径是否正确15                // Console.WriteLine(item.Groups["url"].Value);16                 if (item.Success)17                 {18                     string url = item.Groups["url"].Value;19                     //下载到"d:\1文件夹下,文件名为原来的文件名20                     wc.DownloadFile(url, @"d:\1\" + Path.GetFileName(url));21                 }22             }23             Console.ReadKey();24            25         }

 

练习2:将连续的-替换为一个-。例:010----555-222----444444------------4 替换为:010-555-222-444444-4

1  //练习2:将连续的-替换为一个-。例:010----555-222----444444------------4 替换为:010-555-222-444444-42             string str = "010----555-222----444444------------4";3             str = Regex.Replace(str, "-+", "-");4             Console.WriteLine(str);5             Console.ReadKey();

 

练习3:将《》替换为<>
1 //练习3:将《》替换为<>2             string str = "《论语》、《荀子》、《孝经》、《左传》、《吕氏春秋》、《基督山伯爵》、《林肯传》、《甘地传》、《三国演义》";3             string str2 = Regex.Replace(str,"《(.+?)》","<$1>" );4             Console.WriteLine(str2);5             Console.ReadKey();

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击