Java 字符串不区分大小写和区分大小写替换————一句代码就能搞定(2种方法)

来源:互联网 发布:淘宝客服招聘信息 编辑:程序博客网 时间:2024/05/17 03:02

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

public class ReplaceS {

public static void main(String[] args) {

//如果区分大小写,就是把AabcAaB中的a替换成G

//如果不去分大小写,就是把AabcAaB中的a和A都替换成G

replaceString("AabcAaB","a","G");

replaceStringP("AabcAaB","a","G");

 

}

public static void replaceString(String source,String oldstring,String newstring){ 

        System.out.println("原来的字符串:"+source); 

        

        String result1 = source.replaceAll("(?i)"+oldstring, newstring); //大小写不敏感 

        System.out.println("不区分大小写的替换结果:"+result1); 

       

        String result2 = source.replaceAll(oldstring, newstring);//大小写敏感

        System.out.println("区分大小写的替换结果:"+result2); 

    } 

//使用正则表达式实现不区分大小写替换

public static void replaceStringP(String source, String oldstring, 

   String newstring){ 

Matcher m = Pattern.compile(oldstring, Pattern.CASE_INSENSITIVE).matcher(source); 

String result=m.replaceAll(newstring); 

System.out.println("使用正则表达式不区分大小写的替换结果"+result);

 

 Matcher m1 = Pattern.compile(oldstring, Pattern.CANON_EQ).matcher(source); 

     String result1=m1.replaceAll(newstring); 

     System.out.println("使用正则表达式区分大小写的替换结果"+result1);

}

 

 

第一种(?i)就搞定

原创粉丝点击