How do I get an array of files based on a regular expression?
Author: Deron Eriksson
Description: This Java tutorial describes how to filter files based on a regular expression.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The RegexFileFilter class in the ApacheSW Commons IOS library allows for filtering of files based on a regular expression. This is demonstrated by the RegexFileFilterTest class.

RegexFileFilterTest.java

package test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.apache.commons.io.filefilter.RegexFileFilter;

public class RegexFileFilterTest {

	public static void main(String[] args) throws IOException {
		File directory = new File(".");

		File[] files = directory.listFiles();
		System.out.println("All files and directories:");
		displayFiles(files);

		String pattern = "[tT]est[1-3].txt";
		System.out.println("\nFiles that match regular expression: " + pattern);
		FileFilter filter = new RegexFileFilter(pattern);
		files = directory.listFiles(filter);
		displayFiles(files);

	}

	public static void displayFiles(File[] files) {
		for (File file : files) {
			System.out.println(file.getName());
		}
	}

}

RegexFileFilterTest first displays all files and directories at the root level of my project. After this, it gets all files and directories at the root level of my project that match the regular expression, "[tT]est[1-3].txt". The console output of RegexFileFilterTest is shown here:

Results

All files and directories:
.classpath
.project
bin
docs
lib
src
Test1.txt
test2.txt
Test3.txt
test4.txt

Files that match regular expression: [tT]est[1-3].txt
Test1.txt
test2.txt
Test3.txt