I am checking if a string filename
is safe for saving by checking if it has any strange characters with a Regular expression. It is will be a .json file and should also allow spaces in the file name.
public static boolean fileNameIsSafe(String nameIncExt) {
Matcher m = Pattern.compile("regex?").matcher(nameIncExt);
return m.matches();
}
What would the regular expression be?
There is probably a more elegant solution - I'm not a regex expert, but how about this:
[.]*\\w[\\w| |.]*
Breaking it down:
[.]*
The filename can start with 0 or more '.'s
\w
Then you need at least one word character, which can be az, AZ, 0-9, or _. this prevents file names of '...' or file names that start with a space, or only contain '.'s and spaces.
[\w| |.]*
The remaining file name can have 0 or more word characters, spaces, and/or '.' I'm assuming you can trim off trailing spaces.
Note in Java you'll need to escape the backslashes, so it would look like this:
boolean isSafeFilename = Pattern.matches("[.]*\\w[\\w| |.]*", stringToTest);
I get the feeling that you've never visited this site: Regular-Expressions
Anyway, you can match characters within a character class: [/\\]\\[;']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.