C#中使用正则表达式提取超链接地址

一般在做爬虫或者CMS的时候经常需要提取 href链接或者是src地址。此时可以使用正则表达式轻松完成。

方法一:

Regex reg = new Regex(@"(?is)]*?href=(['""]?)(?[^'""\s>]+)\1[^>]*>(?(?:(?!");
 MatchCollection mc = reg.Matches(yourStr); 
foreach (Match m in mc) { richTextBox2.Text += m.Groups["url"].Value + "\n";//得到href值 richTextBox2.Text += m.Groups["text"].Value + "\n";//得到中间的内容 } 


 

方法二: 

Regex r;        
 Match m;          
 r = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",            
 RegexOptions.IgnoreCase|RegexOptions.Compiled);        
for (m = r.Match(inputString); m.Success; m = m.NextMatch())         
{             
 Console.WriteLine("Found href " + m.Groups[1] + " at " + m.Groups[1].Index);
}
方法三:提取img src的

  
  
Regex reg = new Regex(@"(?i)<img[^>]*?\ssrc\s*=\s*(['""]?)(?<src>[^'""\s>]+)\1[^>]*>");   
 MatchCollection mc = reg.Matches(yourStr);   
 foreach (Match m in mc)    
 {    Console.Write(m.Groups["src"].Value + "\n");   
 }

方法四: 提取img src
///          
  /// 获取Img的路径         
  ///          
  /// Html字符串文本        
  /// 以数组形式返回图片路径        
    public static string[] GetHtmlImageUrlList(string htmlText)       
  {          
   Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); 
   //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签) 
   MatchCollection matches = regImg.Matches(htmlText);
   int i = 0;            
   string[] sUrlList = new string[matches.Count]; 
   //遍历所有的img标签对象            
   foreach (Match match in matches) 
    {                 
    //获取所有Img的路径src,并保存到数组中 
    sUrlList[i++] = match.Groups["imgUrl"].Value;          
    }         
         return sUrlList;     
   }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值