欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java replaceAll不区分大小写

程序员文章站 2022-03-14 23:25:41
...

Java 中replaceAll如何忽略大小写呢?

方式一:在正则表达式前面添加(?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));
	}

 测试结果:
Java replaceAll不区分大小写
            
    
    博客分类: Java replaceAll忽略大小写忽略大小写CASE_INSENSITIVEreplaceAll不区分casereplace忽略大小写
 

 

方式二:使用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;
	}

 测试结果:
Java replaceAll不区分大小写
            
    
    博客分类: Java replaceAll忽略大小写忽略大小写CASE_INSENSITIVEreplaceAll不区分casereplace忽略大小写
 

 

方式三:使用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);

	}

 测试结果:
Java replaceAll不区分大小写
            
    
    博客分类: Java replaceAll忽略大小写忽略大小写CASE_INSENSITIVEreplaceAll不区分casereplace忽略大小写
参考:http://hw1287789687.iteye.com/blog/2150892 

 

  • Java replaceAll不区分大小写
            
    
    博客分类: Java replaceAll忽略大小写忽略大小写CASE_INSENSITIVEreplaceAll不区分casereplace忽略大小写
  • 大小: 62.3 KB
  • Java replaceAll不区分大小写
            
    
    博客分类: Java replaceAll忽略大小写忽略大小写CASE_INSENSITIVEreplaceAll不区分casereplace忽略大小写
  • 大小: 13.3 KB
  • Java replaceAll不区分大小写
            
    
    博客分类: Java replaceAll忽略大小写忽略大小写CASE_INSENSITIVEreplaceAll不区分casereplace忽略大小写
  • 大小: 13 KB