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));
        }
    
    }
  • 相关阅读:
    bat 批处理编写
    dos 命令
    反射
    反爬机制和破解方法汇总
    pandas
    谷歌历史浏览器下载
    python-----pip安装源选择(亲测有效)
    deepin 20.1 系统未安装pip
    python自带库-----os.path
    python 自带库---os库
  • 原文地址:https://www.cnblogs.com/xmqa/p/10275810.html
Copyright © 2011-2022 走看看