java 在Android中替换字符串中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14480944/
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
Replacing special character from a String in Android
提问by Arslan Anwar
I have a String as folder/File Name. I am creating folder , file with that string. This string may or may not contain some charters which may not allow to create desired folder or file
我有一个字符串作为文件夹/文件名。我正在创建带有该字符串的文件夹和文件。此字符串可能包含也可能不包含一些可能不允许创建所需文件夹或文件的章程
e.g
例如
String folder = "ArslanFolder 20/01/2013";
So I want to remove these characters with "_"
所以我想用“_”删除这些字符
Here are characters
这里是字符
private static final String ReservedChars = "|\?*<\":>+[]/'";
What will be the regular expression for that? I know replaceAll(); but I want to create a regular expression for that.
什么是正则表达式?我知道 replaceAll(); 但我想为此创建一个正则表达式。
回答by Kent
Use this code:
使用此代码:
String folder = "ArslanFolder 20/01/2013 ? / '";
String result = folder.replaceAll("[|?*<\":>+\[\]/']", "_");
And the result would be:
结果将是:
ArslanFolder 20_01_2013 _ _ _
you didn't say that space should be replaced, so spaces are there... you could add it if it is necessary to be done.
你没有说应该替换空格,所以空格在那里......如果有必要你可以添加它。
回答by Andrea Aranguren
I used one of this:
我使用了其中之一:
String alphaOnly = input.replaceAll("[^\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\p{Alpha}\p{Digit}]+","");
See this link: Replace special characters
请参阅此链接: 替换特殊字符
回答by Renjith
Try this :
试试这个 :
replaceAll("[\W]", "_");
It will replace all non alphanumeric characters with underscore
它将用下划线替换所有非字母数字字符