0

I am basically trying to filter file names that end with .ack.gz

e.g. String filename = "somefile.ack.gz"

return filename.matches(".ack.gz$");  returns false
return filename.matches("\\.ack\\.gz$");  returns false

Shouldn't one of these match? Not sure what I have missed here...

Daryn
  • 1,551
  • 1
  • 15
  • 21
  • The string doesn't match either of those regular expressions. Your inclusion of `$` suggests you want to test if *part* of the string matches the regular expression, which is not what `matches` tests. Why not just use the `endsWith` method? – kaya3 Sep 27 '20 at 04:31
  • Adding `.*` on the front should help. And the `$` on the end is unnecessary because `matches` will always try to match the entire string. – Kevin Anderson Sep 27 '20 at 04:37

2 Answers2

1

The String.matches method (javadoc) tests to see if the regex matches the entire target string.

But in your example, the regex ".ack.gz$" does not match all of the characters of "somefile.ack.gz". Therefore match returns false.

If you really want to use a regex to do this, then your code should be:

return filename.matches(".*\\.ack\\.gz");

Notes:

  1. The .* matches the first part of the filename.
  2. The \\. says to match a literal . character. If you have no escaping then . matches any single character. A double escape is required because the pattern is being expressed as a Java string literal.
  3. Leading ^ and trailing $ are unnecessary. They are implied by the semantics of match.

But as @kaya points out, it would be better to use String.endsWith (javadoc) here since you don't need regex functionality for this test.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Matches returns true the specified regular expression matches the entire target string. It won't return true if the expression only matches part of the string. So to use matches, you want to supply an expression that matches the whole filename. In your case, that would be:

return filename.matches(".*\\.ack\\.gz");  returns false

The .* at the front of the expression matches anything at the front of the string that isn't matched by the rest of the expression, so that the expression will match the entire target string.

You don't need the $ because the expression already has to match to the end of the string, and so it's redundant.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44