我正在尝试清理包含上传文件名称的String。我这样做是因为文件将从网上下载,而且,我想要规范化名称。这就是我到目前为止所做的:
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 _-...()”。
关于如何调整我的正则表达式的任何想法?
答案 0 :(得分:4)
在循环结束时需要一个Matcher#appendTail。
答案 1 :(得分:2)
一线解决方案:
return badFileName.replaceAll("[^0-9_a-zA-Z\\(\\)\\%\\-\\.]", "");
如果您想将其限制为字母数字和空格:
return badFileName.replaceAll("[^a-zA-Z0-9 ]", "");
干杯:)