[英]Regex not matching the end of a filename
I need to filter out the files in a directory that end with "_done". 我需要过滤出以“ _done”结尾的目录中的文件。
The directory contains three .txt files, namely format1.txt , format2.txt and format2_done.txt that needs to be filtered out. 该目录包含三个.txt文件,即需要过滤掉的format1.txt , format2.txt和format2_done.txt 。
The following sample correctly lists all the files: 下面的示例正确列出了所有文件:
System.out.println("all files: ");
String[] files = folder.list();
for (String item : files) {
System.out.println(item);
}
Output: 输出:
all files:
format1.txt
format2.txt
format2_done.txt
But the following sample: 但是以下示例:
System.out.println("filtered: ");
String[] filteredFiles = folder.list((File folder, String name)
-> {return !(name.matches("_done.txt>"));});
for (String item : filteredFiles) {
System.out.println(item);
}
produces the same output and doesn't filter anything: 产生相同的输出,不过滤任何内容:
filtered:
format1.txt
format2.txt
format2_done.txt
What am I doing wrong? 我究竟做错了什么?
Try to use this regex instead .*_done\\\\.txt$
like this : 尝试改用此正则表达式
.*_done\\\\.txt$
如下所示:
String[] filteredFiles = folder.list((File folder, String name)
-> !name.matches(".*_done\\.txt$")
);
details : 细节 :
.*
zero or more character .*
零个或多个字符 _done\\\\.txt
, note that you should to escape the dot with \\\\
_done\\\\.txt
,请注意,您应使用\\\\
转义点 $
end anchor $
结束锚 Or you can just use String::endsWith : 或者,您可以只使用String :: endsWith :
String[] filteredFiles = folder.list((File folder, String name)
-> !name.endsWith("_done.txt")
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.