利用正则表达式判断网页中的邮箱并输出

tech2024-01-09  79

package zhengze_35; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EmailDemo { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //获取用户的输入 BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:/merge.html"))); //定义邮箱的正则表达式 String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"; Pattern p=Pattern.compile(regex); String email=null; int i=0; while ((email=br.readLine())!=null) { // System.out.println("请输入邮箱"); //获取用户的输入 //判断用户输入的邮箱是否和规范 Matcher m=p.matcher(email); while (m.find()) { System.out.println(email); i++; } // boolean match=email.matches(regex); // if (match) { // System.out.println(email); // i++; // }else { // System.out.println("不合法"); // } } br.close(); System.out.println("共"+i+"个正确格式的邮箱"); } }

d:/merge.html文件 自选,选取一个网站下载到本地目录下,也可以采用以下文件为txt测试使用

waneasu@263.com 2444169361@qq.com 2446565869@163.com

一种较为标准的测试网址中邮箱数量的代码

package work; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class test { public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader br=null; try { Pattern pattern = null; Matcher matcher = null; br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/text/number.html"))); pattern=Pattern.compile("^[a-zA-Z0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)+$"); int i = 0; String line=null; System.out.println("开始读取"); while ((line = br.readLine()) != null) { matcher=pattern.matcher(line); while(matcher.find()) { i++; } } System.out.println(i); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
最新回复(0)