Java replace和replaceAll

package test;

public class ReplaceTest {
    
    public static void main(String[] args) {
        String str1="notice/PublishingImages/第26期(20181112).pdf";
        String str2="notice/PublishingImages/第26期(20181112).pdf";
        String str3="123456.pdf";
        System.out.println("replace:"+str1.replace(str2, str3));//结果:123456.pdf
        System.out.println("replaceAll:"+str1.replaceAll(str2, str3));//结果:notice/PublishingImages/第26期(20181112).pdf
        //此时replaceAll并未出现期待的结果。为什么?
        //replace和replaceAll相同点和区别?
        //1、相同点:替换所有匹配的字符串(都是替换所有)
        //2、不同点:
        //replace支持字符替换,字符串替换
        //replaceAll是正则表达式替换
        String t1="\\";
        System.out.println(t1.replace("\\", "斜杠"));
        System.out.println(t1.replaceAll("\\\\", "斜杠"));
        try{
            System.out.println(t1.replaceAll("\\", "斜杠"));//正则表达式异常    
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        //那么notice/PublishingImages/第26期(20181112).pdf怎么用replaceAll替换成123456.pdf呢?
        String str2_new="notice/PublishingImages/第26期\\(20181112\\)\\.pdf";
        //注意正则表达式对特殊字符的转义:'$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|'
        System.out.println("replaceAll:"+str1.replaceAll(str2_new, str3));
    }

}

 

posted @ 2019-01-16 10:53  迢迢  阅读(3547)  评论(0编辑  收藏  举报