Java中字符串替换方法

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方法中,第一个参数代表的就是普通字符串,不是正则表达式,因此可以精准匹配。