java中replaceAll不區分大小寫替換
阿新 • • 發佈:2019-01-03
Java 中replaceAll如何忽略大小寫呢?
方式一:在正則表示式前面新增(?i)
Java程式碼- @Test
- publicvoid 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"
- }
測試結果:
方式二:使用Matcher 的appendReplacement 方法
Java程式碼- @Test
- publicvoid 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;
- }
測試結果:
方式三:使用Matcher 的replaceAll
Java程式碼- /***
- * 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
- publicvoid 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);
- }
測試結果:
參考:http://hw1287789687.iteye.com/blog/2150892