Search code examples
javaandroidregexfilefilter

Android find a file with a pattern (regex)


Suppose I have files like these in a folder:

  • myfile_mark_1.mp4
  • myfile_john_2.mp4
  • myfile_jake_3.mp4
  • myfile_tristan_4.mp4
  • yourfile_mark_1.mp4

How do I find files where only the names containing "myfile_" in the prefix and suffix would be 3 or less("_3.mp4", "_2.mp4", "_1.mp4", something like this).

So in my program I could get:

  • myfile_mark_1.mp4
  • myfile_john_2.mp4 and
  • myfile_jake_3.mp4

I have tried this one, hoping to get lucky but I didn't get any result. :D

String myDirectory = Environment.getExternalStorageDirectory().getAbsolutePath();
File f = new File(myDirectory);
if (f.exists() && f.isDirectory()){
    final Pattern p = Pattern.compile("myfile_*\\_(^0*(1?\\d|%d)$).mp4"); // I know I really have a stupid mistake on the regex;

    File[] flists = f.listFiles(new FileFilter(){
        @Override
        public boolean accept(File file) {
            return p.matcher(file.getName()).matches();
        }
    });

    String s = "wait a minute, i'm debugging";
}

I hope someone can help out on my problem.


Solution

  • The regex required is quite simple.

    myfile_.*_[123]\\.mp4