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.
You could use 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();
}
});
}
EDIT
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")
EDIT
Starting with Java8 the complete 'return'-part can be written with a lamda-statement:
return root.listFiles((File file) -> p.matcher(file.getName()).matches());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With