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)); } }