正则表达式用于目录中的文件 [英] Regex for files in a directory
本文介绍了正则表达式用于目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用正则表达式获取目录中与给定模式匹配的文件的文件名,而无需手动循环浏览所有文件.
Is it possible to use a regular expression to get filenames for files matching a given pattern in a directory without having to manually loop through all the files.
推荐答案
您可以使用 File.listFiles(FileFilter)
:
public static File[] listFilesMatching(File root, String regex) {
if(!root.isDirectory()) {
throw new IllegalArgumentException(root+" is no directory.");
}
final Pattern p = Pattern.compile(regex); // careful: could also throw an exception!
return root.listFiles(new FileFilter(){
@Override
public boolean accept(File file) {
return p.matcher(file.getName()).matches();
}
});
}
编辑
因此,要匹配如下文件: TXT-20100505-XXXX.trx
其中 XXXX
可以是任意四个连续数字,请执行以下操作:
So, to match files that look like: TXT-20100505-XXXX.trx
where XXXX
can be any four successive digits, do something like this:
listFilesMatching(new File("/some/path"), "XT-20100505-\\d{4}\\.trx")
编辑
从Java8开始,完整的返回"部分可以用lamda语句编写:
Starting with Java8 the complete 'return'-part can be written with a lamda-statement:
return root.listFiles((File file) -> p.matcher(file.getName()).matches());
这篇关于正则表达式用于目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文