Regex that removes all non-alphanumeric, single periods and single slashes

I am trying to rename characters to file names and prevent path manipulation. We take the file name returned from the interface (I know) and analyze it to determine if it is in the specified folder. Therefore, we must make sure that the user does not transfer a file that can exit the specified folder. This means our example for a valid file name:

  • Alphanumeric
  • May contain single slashes in any direction
  • May contain single points, but not pairs.

Thus, the "APP-TEST file .20161115.1" is valid, but the "/../../ test // \" must have some characters deleted before checking the file system.

Here is the regular expression that I have, unfortunately, it removes too much.

public static String validateFilePath(String fileName) {
    return fileName.replaceAll("[^A-Za-z0-9]+[(\\.\\/)\\+2]", "");
}

Thus, "APP-TEST file .20161115.1" becomes "APP-TEST-file0161115.1"

Any help would be assigned.

+4
source share
1 answer

Do you want something like this? (I do not understand what you want!)

String filename = "APP-TEST-file.20161115.1";
// replace two consecutive dots with a single dot
filename = filename.replaceAll("\\.+", ".");
// replace two consecutive forward slash with a single forward slash
filename = filename.replaceAll("/+", "/");
// replace two consecutive baskslash with a backslash
filename = filename.replaceAll("\\\\+", "\\\\");
// allow alphanumeric characters, dots and both type of slashes
filename = filename.replaceAll("[^A-Za-z0-9./\\\\]+", "");
System.out.println(filename);

He prints:

APPTESTfile.20161115.1

If filename="/../../test//\\", then he prints - /././test/\.

+2
source

Source: https://habr.com/ru/post/1663015/


All Articles