gpt4 book ai didi

用于清理上传文件名的 Java 正则表达式

转载 作者:行者123 更新时间:2023-11-30 05:52:48 24 4
gpt4 key购买 nike

我正在尝试清理包含上传文件名称的字符串。我这样做是因为文件将从网上下载,另外,我想规范化名称。这是我目前所拥有的:

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_-...()”。

关于我应该如何调整我的正则表达式有什么想法吗?

最佳答案

在循环结束时需要一个 Matcher#appendTail。

关于用于清理上传文件名的 Java 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11213763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com