Requirement: String should contain only letters , numbers and space.
I have to pass a clean name to another API.
Implementation: Java
I came up with this for my requirement
public static String getCleanFilename(String filename) {
if (filename == null) {
return null;
}
return filename.replaceAll("[^A-Za-z0-9 ]","");
}
This works well for few of my testcase , but want to know am I missing any boundary conditions, or any better way (in performance) to do it.
To answer you’re direct question,
\tfails your method and passes through as “space.” Switch to\s([...\s]and you’re good.At any rate, your design is probably flawed. Instead of arbitrarily dicking with user input, let the user know what you don’t allow and make the correction manual.
EDIT:
If the filename doesn’t matter, take the SHA-2 hash of the file name and use that. Guaranteed to meet your requirements.