Java正则表达式,抓取网页email地址实例

转载自:http://blog.csdn.net/xyang81/article/details/7705960

实现思路:

1、使用java.net.URL对象,绑定网络上某一个网页的地址

2、通过java.net.URL对象的openConnection()方法获得一个HttpConnection对象

3、通过HttpConnection对象的getInputStream()方法获得该网络文件的输入流对象InputStream

4、循环读取流中的每一行数据,并由Pattern对象编译的正则表达式区配每一行字符,取得email地址

[java] view plaincopy
  1. package regex;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.net.URL;  
  6. import java.net.URLConnection;  
  7. import java.util.regex.Matcher;  
  8. import java.util.regex.Pattern;  
  9.   
  10. /** 
  11.  * 网络爬虫,抓取网页中的email地址 
  12.  */  
  13. public class WebCrawlersDemo {  
  14.       
  15.     public static void main(String[] args) throws Exception {  
  16.         URL url = new URL("http://www.tianya.cn/publicforum/content/english/1/129176.shtml");  
  17.         // 打开连接  
  18.         URLConnection conn = url.openConnection();  
  19.         // 设置连接网络超时时间  
  20.         conn.setConnectTimeout(1000 * 10);  
  21.         // 读取指定网络地址中的文件  
  22.         BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  23.         String line = null;  
  24.         String regex = "[a-zA-Z0-9_-]+@\\w+\\.[a-z]+(\\.[a-z]+)?";  // 匹配email的正则  
  25.         Pattern p = Pattern.compile(regex);  
  26.         while((line = bufr.readLine()) != null) {  
  27.             Matcher m = p.matcher(line);  
  28.             while(m.find()) {  
  29.                 System.out.println(m.group());<span style="white-space:pre">  </span>// 获得匹配的email  
  30.             }  
  31.         }  
  32.     }  
  33.   
  34. }  
结果:



posted on 2012-07-01 05:48  yang3wei  阅读(272)  评论(0编辑  收藏  举报