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方法中,第一個參數代表的就是普通字符串,不是正則表達式,因此可以精准匹配。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM