代码如下:
package test;
import java.io.*;
import java.util.regex.*;
public class TestExpress {
public static void main(String[] args) {
try {
String s=null;
BufferedReader buf=new BufferedReader(new FileReader("D:\\测试.html"));
while((s=buf.readLine())!=null) {
prin(s);
}
buf.close() ;
}
catch (IOException e) {
System.out.println("找不到文件");
}
}
private static void prin(String s) throws IOException{
Pattern p=Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$" );
Matcher m=p.matcher(s);
FileWriter fuw= new FileWriter("D:\\put.txt");
while(m.find()){
fuw.write(m.group());
System.out.println(m.group());
}
fuw.close();
}
}
如果正则表达式正确,那么没结果那就是没读到数据咯,bufferedreader是一行一行的读,如果没换行符那肯定是读不到的,最近我就遇到这个情况。
Matcher m=p.matcher(s);
System.out.println(m.groupCount());
输出下找到的组数,看看是不是没找到。
看下正则表达式是否正确,且文件中有符合正则规则的字符串,否则读出的为null
可以用简单的正则表达式 ^[a-z]+$ 文件中保存两行:sdfgasd任意字母 测试下
测试.html文件中只包含小写字母,不要包含任何html标签
正则表达式改为 ^[a-z]+$
我试了下是可以的