Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for files in a directory

Tags:

java

regex

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.

like image 889
n002213f Avatar asked May 28 '10 11:05

n002213f


1 Answers

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());  
like image 106
Bart Kiers Avatar answered Oct 11 '22 04:10

Bart Kiers