gpt4 book ai didi

java - 正则表达式替换 Windows 在文件名中不接受的字符

转载 作者:IT老高 更新时间:2023-10-28 21:01:21 25 4
gpt4 key购买 nike

我正在尝试构建一个正则表达式,它将检测 Windows 不接受作为文件名一部分的任何字符(这些字符对于其他操作系统是否相同?老实说,我不知道)。

这些符号是:

 \ / : * ? "  | 

无论如何,这就是我所拥有的:[\\/:*?\"<>|]

测试员在 http://gskinner.com/RegExr/表明这是有效的。对于字符串 Allo*ha , *符号亮起,表示已找到。我应该输入Allo**ha但是,只有第一个 *会亮起。所以我想我需要修改这个正则表达式来找到提到的字符的所有外观,但我不确定。

你看,在 Java 中,我很幸运拥有 String.replaceAll(String regex, String replacement) 函数。 .描述说:

Replaces each substring of this string that matches the given regular expression with the given replacement.

也就是说,即使正则表达式只找到第一个然后停止搜索,这个函数仍然会找到它们。

例如:String.replaceAll("[\\/:*?\"<>|]","")

但是,我觉得我不能冒这个风险。那么有人知道我可以如何扩展它吗?

最佳答案

由于没有足够好的答案,我自己做了。希望这会有所帮助;)

public static boolean validateFileName(String fileName) {
return fileName.matches("^[^.\\\\/:*?\"<>|]?[^\\\\/:*?\"<>|]*")
&& getValidFileName(fileName).length()>0;
}

public static String getValidFileName(String fileName) {
String newFileName = fileName.replace("^\\.+", "").replaceAll("[\\\\/:*?\"<>|]", "");
if(newFileName.length()==0)
throw new IllegalStateException(
"File Name " + fileName + " results in a empty fileName!");
return newFileName;
}

关于java - 正则表达式替换 Windows 在文件名中不接受的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/754307/

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