0

Given a List containing filenames, I would like to be able to have the number of potential duplicates of a file. A duplicate is defined as a file whose name is either equal or match the naming convention basename(number).extension .

The first step would be to be able to assert whether a filename matches some pattern. I thought I could do it with a regex. Here it is :

    String basename = "file1";
    String extension = "txt";
    String patternExpression = "^%s(\\(\\d+?\\))??\\.%s$";
    Pattern patter = Pattern.compile(String.format(patternExpression, basename, extension));
    assert pattern.matcher("file1.txt").find() : "file1.txt should match";
    assert pattern.matcher("file1(2).txt").find() : "file1(1).txt should match";

In this code sample, the assertions will pass. The problem with this approach happens when the basename contains some characters interpreted by the Regex compiler. I would like to tell the regex compiler to match exactly the basename and to not interpret it.

1) Is that possible ? 2) Isn't there a way to do that more easily ? I feel like there must be an easy way that I'm completely missing...

Thanks for the help !

Gordak
  • 2,060
  • 22
  • 32

0 Answers0