---
title: "Java 字符串不区分大小写和区分大小写替换————一句代码就能搞定（2种方法）"
author: "itlangzicn"
date: "2010-02-04T19:22:49Z"
tags: []
categories: ["编程语言"]
slug: "java-2"
draft: false
lastmod: "2010-02-04T19:22:49Z"
id: 587748
url: "https://itlangzicn.iteye.com/blog/587748"
---

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