我想用Java代码根据文本文件中的某些内容过滤文本文件(我是Java编码的新手)。我已经有了一个正则表达式,但是如果group3在正则表达式的第一个匹配项的任何行中丢失,直到group1更改...我想过滤掉这种文件。
例如。...(文本文件格式)
-----------一些随机文本-------------
-----------一些随机文本-------------
//模式是: group1(可以是任何数字)| group2(从0到n,直到group0更改为止的数字)| group3(一些文本(如果缺少此内容,则过滤文件)) | group4(空还是不重要) | group5(偏移)
10 | 0 | text1 || offset //正则表达式的第一个匹配项
10 | 1 | text4 | textA |偏移
10 | 2 |||偏移量
10 | 3 || textB |偏移量
10 | 4 | text1 | textA |偏移量
2 | 0 | text4 |||偏移量
2 | 1 | text4 |||偏移量
2 | 2 | text4 |||偏移量
2 | 3 | text4 |||偏移 。 。 。
此文件将被过滤掉,因为缺少“ 10 | 2 ||| offset”组3
我的代码
public static void main(String args[]) throws ParseException{
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("folder path");
File[] listOfFiles = folder.listFiles(filter);
for(File f:listOfFiles) {
String fileName = f.toString();
String contents = linebyline(fileName);
String matchgroup0;
final String regex = "(\\d{1,2})\\|(\\d{1,2})\\|(.*?)\\|(.*?)\\(offset)";
final String string = contents;
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
if(matcher.find() && ((matcher.group(3)==null)||(matcher.group(3).length()==0))){ //for the fist match
matchgroup1=matcher.group(1);
System.out.println("rejected txt file1---------->" + fileName);
//for next matching lines with group1 not changing // i know this condition is not proper i need help/suggestion doing this
while(matcher.find() && (matcher.group(1)).equals(matchgroup0) &&((matcher.group(3)==null)||(matcher.group(3).length()==0))){
System.out.println("rejected txt file2---------->" + fileName);
}
}
else{
System.out.println("accepted files---------->" + fileName);
}
}
}
private static String linebyline (String filename) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[10];
try {
reader = new BufferedReader(new FileReader(filename));
while (reader.read(buffer) != -1) {
stringBuilder.append(new String(buffer));
buffer = new char[10];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}