用于清理上载文件名的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());
}
这可以正常工作,但由于一个奇怪的原因,文件的扩展名被删除了。i、 例如,“p%Z-…!$()=?&;+.jpg”最后是“p%Z-…()”
你知道我该如何调整我的正则表达式吗
# 1 楼答案
你需要一个匹配器#appendTail在你的循环末端
# 2 楼答案
单线解决方案:
如果要将其限制为字母数字和空格:
干杯:)