zoukankan      html  css  js  c++  java
  • 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));
        }
    
    }
  • 相关阅读:
    WPF关于“在“System.Windows.Markup.StaticResourceHolder”上提供值时引发了异常。”问题解决办法
    未知的生成错误 因为没有预加载,所以无法解析程序集 GalaSoft.MvvmLight
    C#中的??是什么意思
    WIN10使用管理员权限运行VS2013
    路飞项目
    DRF
    Vue
    dsdffd
    python学习第45天
    python学习第44天
  • 原文地址:https://www.cnblogs.com/xmqa/p/10275810.html
Copyright © 2011-2022 走看看