想把一個(gè)字符串中所有的"\"轉(zhuǎn)換成"/",即把Windows格式的轉(zhuǎn)換成Unix格式.
于是用到String.replaceAll(String regex, String replacement)這個(gè)方法.
如果用path = path.replaceAll("\\", "/"); 會(huì)報(bào)錯(cuò),為什么呢?
在字符串里面,\是轉(zhuǎn)義符.
在正則表達(dá)式里面,\也是轉(zhuǎn)義符.
replaceAll的第一個(gè)參數(shù)是一個(gè)正則表達(dá)式里,想得到正則表達(dá)式中的\,就必須用"\\\\".
即,用\\來得到字符串中的\,用\\\\即可得到正則表達(dá)式中的\.
困擾了幾分鐘,被鐘普一語點(diǎn)破.
在java中要將一個(gè)字符串的中$符號(hào)去除。我是這樣寫的:
String tmp = "-$125402.00";
tmp.replaceAll("$","");
可是執(zhí)行去來的結(jié)果并沒有把$去除。后來找資料才發(fā)現(xiàn)要這樣寫
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);
}
}
就在那個(gè)”[”這里出現(xiàn)錯(cuò)啦!
java.util.regex.PatternSyntaxException: Unclosed character class near
index 0
————————————————————————————————
String的replaceAll方法,第一個(gè)參數(shù)使用的是正則式表達(dá)方法。詳細(xì)可看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));
}
}