001package org.unix4j.unix.find;
002
003import java.io.File;
004import java.io.FileFilter;
005import java.util.regex.Pattern;
006
007import org.unix4j.util.RelativePathBase;
008
009/**
010 * File filter based on file name using regular expressions for the comparison.
011 * Note that find compares the whole path when regex is used, which is supported
012 * by this class through {@link #getRelativePathFilterForBase(RelativePathBase)}
013 * .
014 */
015class RegexFilter implements FileFilter {
016        private final Pattern namePattern;
017
018        /**
019         * Constructor with pattern and ignore-case flag.
020         * 
021         * @param namePattern
022         *            the regex pattern
023         * @param ignoreCase
024         *            true if matching should be case insensitive
025         */
026        public RegexFilter(String namePattern, boolean ignoreCase) {
027                if (ignoreCase) {
028                        this.namePattern = Pattern.compile(namePattern, Pattern.CASE_INSENSITIVE);
029                } else {
030                        this.namePattern = Pattern.compile(namePattern);
031                }
032        }
033
034        /**
035         * Filter if name only is matched, NOT THE WHOLE PATH. Note that find
036         * usually matches the whole path (see
037         * {@link #getRelativePathFilterForBase(RelativePathBase)}).
038         */
039        @Override
040        public boolean accept(File file) {
041                return namePattern.matcher(file.getName()).matches();
042        }
043
044        /**
045         * Returns a file filter that matches the whole (relative) path of the file
046         * instead of just the file name. The path is derived relative to the given
047         * base.
048         * 
049         * @param relativePathBase
050         *            basis for relative paths
051         * @return a filter performing a regexp match on the relative path
052         */
053        public FileFilter getRelativePathFilterForBase(final RelativePathBase relativePathBase) {
054                return new FileFilter() {
055                        @Override
056                        public boolean accept(File file) {
057                                final String relativePath = relativePathBase.getRelativePathFor(file);
058                                return namePattern.matcher(relativePath).matches();
059                        }
060                };
061        }
062}