3

I try to search file with a name like: ENV20120517 every thing you what and finish by .DAT

So i set pattern to: "ENV20120517*.*DAT".

 public boolean accept(File dir, String name) {
    if (pattern != null) {
        return name.matches(pattern);
    }
    return false;
 }

Why with the previous pattern, i get true for: name = "ENV20120516053518.DAT" ?

robert trudel
  • 5,283
  • 17
  • 72
  • 124

3 Answers3

4

String.matches() takes a regular expression, and not a glob pattern.

It so happens that ENV20120517*.*DAT is a valid regex. It does, however, have a different meaning to what you're expecting: it matches any string that starts with ENV2012051 and ends in DAT (the .* matches anything, and the 7* is effectively a no-op).

The following regex is equivalent to the pattern in your question ENV20120517.*[.].*DAT

For some ideas on how to do glob matching in Java, see Is there an equivalent of java.util.regex for "glob" type patterns?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

The parttern should be "ENV20120517.*DAT", because "ENV20120517*.*DAT", the first * matches 0 or more 7 char, so"ENV20120516053518.DAT".matches("ENV20120517*.*DAT") is true.

Liu guanghua
  • 981
  • 1
  • 9
  • 18
  • if i put: ENV20120517.*DAT, there are no file found – robert trudel May 24 '12 at 08:51
  • you run: String pattern = "ENV20120517.*DAT"; for (int i = 100000; i < 1000000; i++) { String fileName = "ENV20120517" + i + ".DAT"; if (!fileName.matches(pattern)) { System.out.println(fileName + " doesn't match pattern: " + pattern); } } – Liu guanghua May 25 '12 at 01:18
0

Try

pattern = "ENV20120517.*\\.DAT"

Or more strictly:

pattern = "^ENV20120517.*\\.DAT$"
fabregaszy
  • 496
  • 6
  • 23