且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文件中提取email地址

更新时间:2022-04-28 06:15:34

在网上看了一篇文章是关于提示email的,看了以后觉得作者的正则表达式有些问题,所以自己就修改了一下,源码如下:


  1. package com.sucre.api.test;   
  2. /**   
  3.  * 提取邮件地址  
  4.  * @author 乔磊   
  5.  * @version create time:2011-1-7 上午10:55:05   
  6.  *   
  7.  */ 
  8.  
  9. import java.io.File;  
  10. import java.io.IOException;  
  11. import java.util.regex.Matcher;  
  12. import java.util.regex.Pattern;  
  13. import org.apache.commons.io.FileUtils;  
  14.  
  15. public class EmailParser {  
  16.       
  17.     private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");  
  18.     public static void main(String[] args) throws IOException {  
  19.         String txt = FileUtils.readFileToString(new File(args[0]));  
  20.         Matcher matchr = emailer.matcher(txt);  
  21.         while (matchr.find()) {  
  22.             String email = matchr.group();  
  23.             System.out.println(email);  
  24.         }  
  25.     }  
  26.  

作者先前的正则表达式是这样的


  1. private final static Pattern emailer = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");  

这样在提取的时候会把aa@.com这样形式的email也提取出来的,所以是不正确的。



本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/473736,如需转载请自行联系原作者