原文:http://hw1287789687.iteye.com/blog/2150897java
Java 中replaceAll如何忽略大小寫呢?正則表達式
方式一:在正則表達式前面添加(?i)app
- @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 方法spa
- @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);
-
- }
-
-
-
-
-
-
-
- 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;
- }
測試結果:
blog
方式三:使用Matcher 的replaceAll圖片
-
-
-
-
-
-
-
-
- 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);
-
- }
測試結果:
get