Problem with regex being used to filter filenames ...

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.

*/

publicclass RegexFilenameFilterimplements FilenameFilter{

privatestaticfinal 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.

*/

publicboolean accept(File directory, String fileName){

return regexPattern.matcher(fileName).matches();

}

}

[3344 byte] By [rweavera] at [2007-10-3 7:43:35]
# 1

public static void main(String args[])

{

ArrayList<String> al = new ArrayList<String>();

al.add( "sfsd.txt" );

al.add( "dfde.doc" );

al.add( "sfsd.xml" );

al.add( "sfsd.txt" );

al.add( "win.xml" );

Iterator i = al.iterator();

while ( i.hasNext() )

{

String s = (String) i.next();

if ( s.endsWith( ".xml" ) )

{

System.out.println( s );

}

}

}

Norweeda at 2007-7-15 2:44:42 > top of Java-index,Java Essentials,Java Programming...
# 2
Use negative lookbehind instead:// Only deal with files that don't end with .xmlfileList = dir.listFiles(new RegexFilenameFilter(".*(?<![.]xml)$"));Regards>
jfbrierea at 2007-7-15 2:44:42 > top of Java-index,Java Essentials,Java Programming...