Java 中replaceAll 忽略⼤⼩写
Java 中replaceAll 如何忽略⼤⼩写呢?
⽅式⼀:在正则表达式前⾯添加(?i)
测试结果
:
⽅式⼆:使⽤Matcher 的appendReplacement ⽅法 测试结果
:
Java 代码
1.
@Test 2.
public void test_replaceAll33(){ 3.
String input = "I like Java,jAva is very easy and jaVa is so popular."; 4.
String replacement="cccc"; 5.
6.
System.out.println(input); 7.
System.out.placeAll("(?i)java", replacement)); 8. }
Java 代码
1.
@Test 2.
public void test_replaceAll(){ 3.
String input = "I like Java,jAva is very easy and jaVa is so popular."; 4.
String regex = "java"; 5.
String replacement="cccc"; 6.
7.
StringBuffer sb =replaceAll2(input, regex, replacement); 8.
System.out.println(input); 9.
System.out.println(sb); 10.
11.
} 12.
/*** 13.
* replaceAll,忽略⼤⼩写 14.
* @param input 15.
* @param regex 16.
* @param replacement 17.
* @return 18.
*/ 19.
public StringBuffer replaceAll2(String input,String regex,String replacement){ 20.
Pattern p = Patternpile(regex,Pattern.CASE_INSENSITIVE); 21.
Matcher m = p.matcher(input); 22.
StringBuffer sb = new StringBuffer(); 23.
boolean result = m.find(); 24.
while (result) 25.
{ 26.
m.appendReplacement(sb, replacement); 27.
result = m.find(); 28.
} 29.
m.appendTail(sb); 30.
return sb; 31. }
⽅式三:使⽤Matcher 的replaceAll 测试结果
:
Java 代码
1.
/*** 2.
* replaceAll,忽略⼤⼩写 3.
* 4.
replaceall()* @param input 5.
* @param regex 6.
* @param replacement 7.
* @return 8.
*/ 9.
public String replaceAll3(String input, String regex, String replacement) { 10.
Pattern p = Patternpile(regex, Pattern.CASE_INSENSITIVE); 11.
Matcher m = p.matcher(input); 12.
String result = m.replaceAll(replacement); 13.
return result; 14.
} 15.
16.
@Test 17.
public void test_replaceAll3() { 18.
String input = "I like Java,jAva is very easy and jaVa is so popular."; 19.
String regex = "java"; 20.
String replacement = "cccc"; 21.
22.
String sb = replaceAll3(input, regex, replacement); 23.
System.out.println(input); 24.
System.out.println(sb); 25.
26. }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论