简体   繁体   中英

regex to match file names

I have a java class and I want to read files which have names starting with "home-search-log.log". So I have written this code.

  File dir = new File("D:\\");
   File[] foundFiles = dir.listFiles(new FileFilter() {
    public boolean accept(File file) {

        return Pattern.compile("^(home-search-log.log)").matcher(file.getName()).matches();
    }
   });
   for (File file : foundFiles) {
       System.out.println(file.getName());
   }

But it is returning only one file which has exact name as given. Name of my other file is "home-search-log.log.2013-04-12" but it is not returned by this pattern. Where am I wrong?

我认为以下代码可能更好:

return file.getName().startsWith("home-search-log.log");

尝试以下正则表达式。

System.out.println("home-search-log.log.2013-04-12".matches("^home-search-log.*"));

Try something like this:

"^(home-search-log\\.log.*)"

First you need to escape the special chars used in regex ("-",".") and add the end to specify that you want to match anything ".*" so in this case it should match anything from "home-search-log.log" to "home-search-log.logsomething"

使用方法如下;

"home-search-log.log((.\\d[4]-\\d[2]-\\d[2])?)"

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