Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problem with regex being used to filter filenames ...

807607Oct 18 2006 — edited Oct 18 2006
I wrote a simple FilenameFilter that takes a regular expression (String) in it's constructor. It uses that regex to determine which files to return when a directory is read using the listFiles(FilenameFilter) syntax.

The problem I'm having is probably with my regex. If I use a regex like ".*[.]xml", the filter appears to work as I would expect: I get only files that end in XML.

If on the other hand I try to do a little more complex regex to get all the files that don't end in ".xml", it seems to match everything.

In my code, I am doing the following:
                // Only deal with files that don't end in XML
                fileList = dir.listFiles(new RegexFilenameFilter(".*[.](?!xml).*$"));
Where I'm using the regex ".*[.](?!xml).*$", which should match any string that doesn't end with .xml.

My RegexFilenameFilter follows:
/*
 * RegexFilenameFilter.java
 *
 * Created on May 26, 2006, 10:27 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.jmmdhs.util;

import java.io.File;
import java.io.FilenameFilter;

import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * Regular Expression FilenameFilter - allows filtering directory by regex.
 */
public class RegexFilenameFilter implements FilenameFilter {
    
    private static final Logger logger = Logger.getLogger(RegexFilenameFilter.class);
    
    private String patternString = null;
    private Pattern regexPattern;  
    
    /**
     * Constructor that takes a String containing the regex for matching
     * @param regexString Regular expression string.
     */
    public RegexFilenameFilter(String regexString) {
        logger.debug("Constructing RegexFilenameFilter with expression '" + regexString + "'");
        patternString = regexString;
        regexPattern = Pattern.compile(patternString);
    }
    
    /**
     * Method returns true if the pattern matches.
     * @param directory Directory to match
     * @param fileName Name of the file to match
     * @return Boolean indicating match.
     */
    public boolean accept(File directory, String fileName) {
        return regexPattern.matcher(fileName).matches();      
    }
    
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 15 2006
Added on Oct 18 2006
2 comments
849 views