If you have to identify / find files in one directory based on many different regular expression patterns in a file name, the below class might be of interest for you.

It is implementing the Java interface FilenameFilter in combination with the classes regex.Matcher and regex.Pattern to create a new class called FilenamePattern. I am usually not praising myself but I like the name of this class.

In its current version the FilenamePattern has an acceptable performance for a few patterns, which file names should be compared against.

If you however intend to use it to search for many patterns in file names in one or more directories, I suggest to compile all Pattern objects at initialization time and hold them in a separate collection. In the below version the patterns are compiled for each handed file in a handed directory. This is of course inefficient.

For the sake of simplicity one could argue that it would be easier to use methods offered by the class String in order to match file names against Strings. For example the method "matches" accepts regex patterns. However it might be a bit easier to use, they will also have to compile a pattern every time this method is called if it is not automatically cached by Java. With below solution you at least have the freedom to cache Patterns and a FilenameFilter is easy to use.

Version & Remarks

Version Date Description
0.2 2015-02-01

This version is now expected to be faster than the first version 0.1. I changed the initialization of the class in order to compile handed regular expressions into Patterns only once instead of compiling it for each tested file in a directory. Also logging has been added in order to allow more detailed feedback to calling methods.

Source Code

Below source code serves as an example for how regular expressions can be incorporated into an implementation of the interface FilenaemFilter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package de.consulting.bolte.io;
 
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
 
/**
 * This class implements the interface FilenameFilter using regular expressions
 * to identify / find files, which meet filter conditions handed in a
 * collection.
 
 * @author Alexander Bolte - Bolte Consulting (2015)
 
 */
public class FilenamePattern implements FilenameFilter {
 
	@Override
	/**
	 * If a file is accepted or not is decided by this method.
	 * Every files name in a directory the FilenameFilter is 
	 * applied on is compared against every pattern 
	 * in a globally available collection.
	 
	 * If a file name matches one of the patterns it is compared against, 
	 * comparison is stopped and a corresponding file is accepted.
	 */
	public boolean accept(File dir, String name) {
		boolean ret = false;
		Matcher aMatch;
 
		for (int i = 0; i < this.filenamePattern.size(); i++) {
			aMatch = filenamePattern.get(i).matcher(name);
			ret = aMatch.find();
			if (ret) {
				break;
			}
		}
 
		aMatch = null;
		return ret;
	}
 
	/**
	 * Sets the collection holding all patterns which are used to search files.
	 
	 * @param filePattern
	 *            an ArrayList providing regular expression patterns all
	 *            file names in a directory should be compared against.
	 */
	public void setFilenamePattern(ArrayList filePattern) {
		Pattern fp = null;
		filenamePattern = new ArrayList();
 
		this.filenameRegEx = filePattern;
		for (String regex : filenameRegEx) {
			fp = validateAndCompile(regex);
			if (fp != null) {
				filenamePattern.add(fp);
			}
		}
	}
 
	/**
	 * Applies simple validation and attempts to compile given regular
	 * expression.
	 
	 * This method provides logging for each handed regular expression in order
	 * to allow getting results even, if many expressions are handed to this
	 * class.
	 
	 * The logger used by all methods in this class is called
	 * FilenamePattern.class.getName().
	 
	 * @param regex
	 *            a String providing a regular expression, which should be
	 *            compiled.
	 * @return a successfully compiled Pattern or null, if compilation fails.
	 */
	private Pattern validateAndCompile(String regex) {
		Pattern fp = null;
		Logger log = Logger.getLogger(FilenamePattern.class.getName());
 
		try {
			if (regex != "") {
				fp = Pattern.compile(regex);
			} else {
				log.log(Level.WARNING, "Empty regex not allowed ''\tN/A");
			}
		} catch (PatternSyntaxException e) {
			log.log(Level.SEVERE, "Could not compile regex '" + regex
					+ "' into a pattern\t" + e.getMessage());
		}
 
		return fp;
	}
 
	/**
	 * Returns current ArrayList holding all regular expression patterns
	 * of an instantiation of this class.
	 
	 * @return the filenamePattern an ArrayList holding all regular
	 *         expressions file names of all files in a given directory will be
	 *         compared against.
	 */
	public ArrayList getFilenameRegex() {
		return filenameRegEx;
	}
 
	/**
	 * A globally available collection of type ArrayList holding all
	 * patterns used to find files in a directory.
	 */
	ArrayList filenameRegEx;
	ArrayList filenamePattern;
}

Referenced Java classes

Links to important referenced classes can be found below.

http://docs.oracle.com/javase/7/docs/api/java/io/FilenameFilter.html

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html