java 从字符串中删除无效字符 (("\\/:*?\"<>|") ) 以将其用作 FileName
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31563951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing invalid characters (("\\/:*?\"<>|") ) from a string to use it as a FileName
提问by curious
How to remove invalid characters from a String , so that it can be used as a file name ?
the invalid characters include ("\\/:*?\"<>|")
.
如何从 String 中删除无效字符,以便将其用作文件名?
无效字符包括 ("\\/:*?\"<>|")
.
回答by CoderCroc
You can try this,
你可以试试这个
String fileName = "\/:*AAAAA?\"<>|3*7.pdf";
String invalidCharRemoved = fileName.replaceAll("[\\/:*?\"<>|]", "");
System.out.println(invalidCharRemoved);
OUTPUT
输出
AAAAA37.pdf
回答by Sanjay Rabari
You can use regex
您可以使用正则表达式
String s= string.replaceAll("[\\/:*?\"<>|]", "");
回答by Anonymous Coward
You should not try to second guess the user. If the provided filename is incorrect just show an error message or throw an exception as appropriate.
您不应该尝试再次猜测用户。如果提供的文件名不正确,则仅显示错误消息或根据需要抛出异常。
Removing those invalid characters from a suplied filename does in no way ensure that the new filename is valid.
从提供的文件名中删除那些无效字符并不能确保新文件名有效。
回答by Thomas Weller
You can replace characters by replaceAll()
:
您可以通过replaceAll()
以下方式替换字符:
@Test
public void testName() throws Exception
{
assertEquals("", "\/:*?\"<>|".replaceAll("[\\/:*?\"<>|]", ""));
}
however, note that
但是,请注意
.
and..
on its own are also invalid, although you allow dots- for using the file with WebDAV,
&
is also a disallowed character (might be Microsoft specific) COM1
is also an invalid file name, although it has legal characters only (also applies toPRN
,LPT1
and similar) (might be Microsoft specific)$MFT
and similar are also invalid, although you can use$
in general (might be NTFS specific)
.
并且..
本身也是无效的,尽管你允许点- 用于将文件与 WebDAV 一起使用,
&
也是不允许的字符(可能是 Microsoft 特定的) COM1
也是无效的文件名,尽管它只有合法字符(也适用于PRN
,LPT1
和类似的)(可能是 Microsoft 特定的)$MFT
和类似的也是无效的,尽管您可以$
在一般情况下使用(可能是特定于 NTFS 的)