我想清理包含上傳文件名的字符串。我這樣做是因爲這些文件將從網上下載,另外,我想規範化名稱。這是我到目前爲止:Java正則表達式來清理上傳的文件名
private String pattern = "[^0-9_a-zA-Z\\(\\)\\%\\-\\.]";
//Class methods & stuff
private String sanitizeFileName(String badFileName) {
StringBuffer cleanFileName = new StringBuffer();
Pattern filePattern = Pattern.compile(pattern);
Matcher fileMatcher = filePattern.matcher(badFileName);
boolean match = fileMatcher.find();
while(match) {
fileMatcher.appendReplacement(cleanFileName, "");
match = fileMatcher.find();
}
return cleanFileName.substring(0, cleanFileName.length() > 250 ? 250 : cleanFileName.length());
}
這工作正常,但由於一個奇怪的原因文件的擴展被擦除。即「p%Z_-...#!$()='& + .jpg」結束爲「p%Z _-...()」。
任何想法,我應該如何調整我的正則表達式?
張貼我開始這個問題後不知道爲什麼沒」 t我使用replaceAll ... – Gamb
我要說的是replaceAll就是我在這種情況下會用到的。 – carmenism
上面的代碼可以通過使用'的replaceAll歸結爲一個兩襯墊( 「[^ 0-9A-ZA-Z \\ + \\(\\)_ \\ - ]」, 「」) ' – Gamb