String url = "d://test////hello\\\hello";
String separator = File.separator;
url = url.replaceAll("\\*", separator);
url = url.replaceAll("/+", separator);
我想格式化那些url
,但是当我尝试使用时发生错误replaceAll("/+", separator)
。我试图逃脱"/"
,"\\/"
它仍然不起作用..
这是来自控制台的异常:
Exception in thread "main" **java.lang.StringIndexOutOfBoundsException**: String index out of range: 1
at java.lang.String.charAt(String.java:686)
at java.util.regex.Matcher.appendReplacement(Matcher.java:703)
at java.util.regex.Matcher.replaceAll(Matcher.java:813)
at java.lang.String.replaceAll(String.java:2189)
现在它可以工作了
String separator = null;
if(File.separator.equals("/")) {
separator = "/";
url = url.replaceAll("/+", separator);
url = url.replaceAll("\\\\+", separator);
} else {
separator = Matcher.quoteReplacement(File.separator);
url = url.replaceAll("/+", separator);
url = url.replaceAll("\\+", separator);
}
:) 它适用于 javascript
var i = "d:\\ad////df";
alert(i.replace(/\/+/g, '\\'));