ITeye博客

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

itlangzicn · 2010-02-04 19:22 · Java · 编程语言 · Markdown

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)就搞定

评论(2)

  1. #2 楼 · cengjing0616k · 2011-09-23 14:22

    不错不错不错不错不错不错

  2. #1 楼 · xiaolongfeixiang · 2010-02-06 21:22

    呵呵 看到了JDK API的说明了:

    利用的就是CASE_INSENSITIVE的参数。

    [b]CASE_INSENSITIVE[/b]

    public static final int CASE_INSENSITIVE启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。

    通过嵌入式标志表达式 (?i) 也可以启用不区分大小写的匹配。

    指定此标志可能对性能产生一些影响。

    学习了。支持一下

评论功能维护中,当前仅展示历史评论。