zoukankan      html  css  js  c++  java
  • Java 中replaceAll忽略大小写(转)

    https://blog.csdn.net/u012109105/article/details/47003949

      方式一:在正则表达式前面添加(?i)

    @Test  
    public void test_replaceAll33(){  
        String input = "I like Java,jAva is very easy and jaVa is so popular.";  
        String replacement="cccc";  
    
        System.out.println(input);  
        System.out.println(input.replaceAll("(?i)java", replacement));  
    }

      测试结果

      方式二:使用Matcher 的appendReplacement 方法

    @Test  
    public void test_replaceAll(){  
        String input = "I like Java,jAva is very easy and jaVa is so popular.";  
        String regex = "java";  
        String replacement="cccc";  
          
        StringBuffer sb =replaceAll2(input, regex, replacement);  
        System.out.println(input);  
        System.out.println(sb);  
    
    }  
    /*** 
     * replaceAll,忽略大小写 
     * @param input 
     * @param regex 
     * @param replacement 
     * @return 
     */  
    public StringBuffer replaceAll2(String input,String regex,String replacement){  
         Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);  
            Matcher m = p.matcher(input);  
            StringBuffer sb = new StringBuffer();  
            boolean result = m.find();  
            while (result)  
            {  
                m.appendReplacement(sb, replacement);  
                result = m.find();  
            }  
            m.appendTail(sb);  
            return sb;  
    }

      测试结果

      方式三:使用Matcher 的replaceAll

    /*** 
     * replaceAll,忽略大小写 
     *  
     * @param input 
     * @param regex 
     * @param replacement 
     * @return 
     */  
    public String replaceAll3(String input, String regex, String replacement) {  
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);  
        Matcher m = p.matcher(input);  
        String result = m.replaceAll(replacement);  
        return result;  
    }  
    
    @Test  
    public void test_replaceAll3() {  
        String input = "I like Java,jAva is very easy and jaVa is so popular.";  
        String regex = "java";  
        String replacement = "cccc";  
    
        String sb = replaceAll3(input, regex, replacement);  
        System.out.println(input);  
        System.out.println(sb);  
    
    }

      测试结果

    ---

  • 相关阅读:
    数据结构-索引
    CAS自旋volatile变量
    深入理解AQS
    EL表达式
    JSTL 核心标签库 使用
    JSP 九个隐含JSP对象
    jsp基本语法总结
    Commons FileUpLoad 两种上传方式解
    Servlet 异常处理
    Servlet 过滤器 Filter
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/14600835.html
Copyright © 2011-2022 走看看