怎样用java正则表达式从文档中提取需要的信息?
展开全部
给你代码,在一个文件夹中找那个文件中有人要查找的字符串.
-------------------------------------------------------------------
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test2 {
public static void main(String args[]) throws Exception {
execute(new File("H:\\test"), "find");
}
public static void execute(File root, String findStr) throws Exception {
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
continue;
}
if (fileHandler(files[i], findStr)) {
System.out.println(files[i].getName());
}
}
}
public static boolean fileHandler(File file, String findStr)
throws Exception {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
boolean result = false;
while (br.ready()) {
String line = br.readLine();
result = findCount(line, findStr);
if (result) {
break;
}
}
br.close();
fr.close();
return result;
}
public static boolean findCount(String line, String findStr) {
Pattern p = Pattern.compile(findStr);
Matcher m = p.matcher(line);
int count = 0;
while (m.find()) {
if (!"".equals(m.group())) {
return true;
}
}
return false;
}
}
-------------------------------------------------------------------
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test2 {
public static void main(String args[]) throws Exception {
execute(new File("H:\\test"), "find");
}
public static void execute(File root, String findStr) throws Exception {
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
continue;
}
if (fileHandler(files[i], findStr)) {
System.out.println(files[i].getName());
}
}
}
public static boolean fileHandler(File file, String findStr)
throws Exception {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
boolean result = false;
while (br.ready()) {
String line = br.readLine();
result = findCount(line, findStr);
if (result) {
break;
}
}
br.close();
fr.close();
return result;
}
public static boolean findCount(String line, String findStr) {
Pattern p = Pattern.compile(findStr);
Matcher m = p.matcher(line);
int count = 0;
while (m.find()) {
if (!"".equals(m.group())) {
return true;
}
}
return false;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询