java如何获得文件中的所有email邮箱号?
1、首先我们要明确怎么来获取。对,就是正则表达式:
我们先声明一个变量private final static Pattern emailer = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
2、然后我们将文档中的文件以字符串的形式读取出来:
String txt = FileUtils.readFileToString(new File("E:/tst.txt"));
3、通过正则表达式匹配:
Matcher matchr = emailer.matcher(txt);
4、如果匹配,则找到邮箱,并且输出:
while (matchr.find())
{
String email = matchr.group();
System.out.println(email);
}
5、整个代码如下:
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
public class EmailParser {
private final static Pattern emailer = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String txt = FileUtils.readFileToString(new File("E:/tst.txt"));
Matcher matchr = emailer.matcher(txt);
while (matchr.find()) {
String email = matchr.group();
System.out.println(email);
}
}
}
6、如果您觉得小编帮助到了您,请点个赞吧!谢谢!