想把一個字符串中所有的"\"轉換成"/",即把Windows格式的轉換成Unix格式.
于是用到String.replaceAll(String regex, String replacement)這個方法.
如果用path = path.replaceAll("\\", "/"); 會報錯,為什么呢?
在字符串里面,\是轉義符.
在正則表達式里面,\也是轉義符.
replaceAll的第一個參數是一個正則表達式里,想得到正則表達式中的\,就必須用"\\\\".
即,用\\來得到字符串中的\,用\\\\即可得到正則表達式中的\.
困擾了幾分鐘,被鐘普一語點破.
在java中要將一個字符串的中$符號去除。我是這樣寫的:
String tmp = "-$125402.00";
tmp.replaceAll("$","");
可是執行去來的結果并沒有把$去除。后來找資料才發現要這樣寫
tmp.replaceAll("\\$","")才可以。
public class test {
public static void main(String[] args) {
String str=”F[ACE=color]dddddddddddddd[/FACE]“;
str=str.replaceAll(”[”,”<”);
System.out.print(str);
}
}
就在那個”[”這里出現錯啦!
java.util.regex.PatternSyntaxException: Unclosed character class near
index 0
————————————————————————————————
String的replaceAll方法,第一個參數使用的是正則式表達方法。詳細可看JDK文檔。
上例改為replaceAll(”\\Q[\\E”,”<”);
public class PathTrackle
{
public static String existPathTrackle(String path){
String tempString = path.replaceAll("\\\\", "/");
String returnString = tempString.replaceAll("/+|", "/");
return returnString;
}
public static void main(String args[]){
String a="ab/cd/";
String b="\\\\\\dawson\\\\";
String c="http://///////////c/d//ab//kk//";
System.out.println(existPathTrackle(c));
}
}