First of all, I know that there are tons of regex threads here in the stackoverflow and I checked a bunch of it, but it is being really hard to match the correct sentence here.
What I am currently trying to do is a match these characters: - a-z - A-Z - 0-9 - .()~-_[]
Based in this regex, what will be done after is replace all the characters that are not matching here by no space.
The file names that I am using as an example are: - 12345677-fieberthermometer-fuer-schlaefe-und-ohr-digital-mapa-nuk-d0@#$%"&*()!ßöäüÄÜÖ"'][}{<>:;,º.jpg
private static final String FOLDER = "/path/to/my/folder";
private static final String URL_VALID_REGEX = "a-zA-Z0-9\\.\\(\\)\\[\\]\\-~_";
public static void main(String[] args) {
File imagesDirPath = new File(FOLDER);
Pattern p = Pattern.compile("[" + URL_VALID_REGEX + "]");
final String[] listImages = imagesDirPath.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
Matcher m = p.matcher(name);
if (!m.matches()){
File renamedFile = new File(FOLDER + File.separator + name);
name = name.replaceAll("[^" + URL_VALID_REGEX + "]", "");
renamedFile.renameTo(new File(FOLDER + File.separator + name));
}
System.out.println(name);
final String extension = FilenameUtils.getExtension(name);
final boolean isAcceptedExtesion = getAcceptedFileFormatList().contains(extension);
final long lastModified = new File(dir, name).lastModified();
return isAcceptedExtesion;
}
});
}
As you can see in the code, the replace for the characters occurs with a negation of the regex for valid, but I'm also not sure if that is how it should be since all the matches are always false.
1st problem: The match is always false even though the file name is correct, which leads to create a new file and change the last modification date, which is important to remain the same
2nd problem: The comma and asterisk always remain in the file name, but this is also probably due the wrong regex
Example of a valid name: - 12345677-fieberthermometer-fuer-schlaefe-und-ohr-digital-mapa-nuk-d0_~()][.jpg
What am I missing here that I am not able to find?