Java String类中有个方法叫:replaceAll,从表面上看,他的意思是把所有的regex替换成replacement。
1 public String replaceAll(String regex, String replacement) { 2 return Pattern.compile(regex).matcher(this).replaceAll(replacement); 3 }
但事实上,它并没有做到:
1 public static void main(String[] args) { 2 String str="aaa"; 3 System.out.println(str.replaceAll("aa", "a")); 4 }
结果是:
aa
所以,这个方法是骗人的。
真正的replaceAll应该是这样的:
1 void replaceAll(String str, String regex, String replacement) { 2 if (str.contains(regex)) { 3 str = str.replaceAll(regex, replacement); 4 replaceAll(str, regex, replacement); 5 } else { 6 System.out.println(str); 7 } 8 }
test.java
1 public class test { 2 3 public static void main(String[] args) { 4 String str = "aaattaaaa"; 5 String regex = "aa"; 6 String replacement = "a"; 7 replaceAll(str, regex, replacement); 8 } 9 10 public static void replaceAll(String str, String regex, String replacement) { 11 if (str.contains(regex)) { 12 str = str.replaceAll(regex, replacement); 13 replaceAll(str, regex, replacement); 14 } else { 15 System.out.println(str); 16 } 17 } 18 }
输出:
atta
tool:
public static String replaceAll(String str, String regex, String replacement) { if (str.contains(regex)) { str = str.replaceAll(regex, replacement); str=replaceAll(str, regex, replacement); } return str; }
纯属娱乐 :)
时间: 2024-11-09 03:13:07