网页爬虫(蜘蛛)

本文介绍了一种使用Java正则表达式从文本及网页中解析电子邮件地址的方法。通过两个示例,一是从本地文件中读取并解析邮件地址,二是从指定网址抓取页面内容并解析邮件地址,展示了如何利用Pattern和Matcher类实现这一功能。

所用的知识点有:io,正则,Pattern,url

package com.regexTest;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Zhizhu {
    public static void main(String[] args) throws IOException {
        test_1();//本地
        test_2();//网页
    }

    private static void test_2() throws IOException {
        URL url=new URL("http://www.cnblogs.com/skyseraph/p/6443596.html");
        URLConnection conn=url.openConnection();
        
        BufferedReader bufin=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line=null;
        
        String mailreg="\\w+@\\w+(\\.\\w+)+";
        Pattern p=Pattern.compile(mailreg);
        
        while((line=bufin.readLine())!=null){
            p.matcher(line);
            Matcher m=p.matcher(line);//匹配器
            while(m.find()){
                System.out.println(m.group());//返回上面被匹配到的输入子序列
            }
        }
    }

    private static void test_1() throws IOException {
        // 1.将文本读取到内存缓冲区
        BufferedReader br=new BufferedReader(new FileReader("D:\\BaiduYunDownload\\mail.txt"));
        
        String line=null;
        //书写正则表达式
        String mailreg="\\w+@\\w+(\\.\\w+)+";
        
        //将规则封装成对象
        Pattern p=Pattern.compile(mailreg); 
        
        while((line=br.readLine())!=null){
            //让正则对象和要作用的字符串关联,获取匹配器对象
            p.matcher(line);
            Matcher m=p.matcher(line);
            //当找到,
            while(m.find()){
                System.out.println(m.group());
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/boyhan/p/6445919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值