replaceAll方法
public String replaceAll(String regex, String replacement)
replace方法
public String replace(CharSequence target, CharSequence replacement)
example
public static void main(String[] args) {
System.out.println("hello$".replaceAll("$",""));
System.out.println("hello$".replace("$",""));
System.out.println("hello$".replaceAll("\\$",""));
}
hello$
hello
hello
結論
replaceAll方法中,第一個參數為字符串形式的正則表達式,按照正則來匹配的,'$'在正則中為特殊符號,表示字符串的結束位置,所以例子中並不會被空字符串替換;但是加上轉義字符'\$',表示浦東字符串'$',就可以匹配上了。而replace方法中,第一個參數代表的就是普通字符串,不是正則表達式,因此可以精准匹配。