简体   繁体   中英

in java using asterisk and question marks to match the name of a file

I want to write in java something like this:

public class MyMatcher 
{
   public static boolean isMatching(String filename, String param) { 
      ...
   }
}

filename would be the name of a file without the directory (eg: readme.txt, shares.csv, a nice song.mp3, ...)

param would be something like "*.mp3" to say all of the files ending with .mp3 and so on.

Note: param is not regular expression statement is more like the usual way of searching files like on textpad or eclipse or even the dos dir.

Can somebody suggest either how to do this or if there is some opensource library to do this ?

String pattern = param.replaceAll ("\\*", ".*").replaceAll ("\\?", ".");
return filename.matches (pattern); 

Apache Commons IO has a WilcardFileFilter :

The wildcard matcher uses the characters '?' and '*' to represent a single or multiple wildcard characters.

Example from the javadoc:

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*test*.java~*~");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
  System.out.println(files[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM