String類的三個內建正則表達式工具: 1.matches()方法 示例:檢查一個句子是否以大寫字母開頭,以句號結尾 1 public static boolean checkFormat(String sentence){ 2 return sentence.matches("^[A-Z].+\
String類的三個內建正則表達式工具:
1.matches()方法
示例:檢查一個句子是否以大寫字母開頭,以句號結尾
1 public static boolean checkFormat(String sentence){ 2 return sentence.matches("^[A-Z].+\\.$"); 3 }
2.split()方法
示例:以空格分割knights字元串並以數組形式返回
1 public static void test(){ 2 String knights = 3 "Then, when you have found the shrubbery," 4 + "you must cut down the mightiest tree in the forest... " 5 + "with... a herring"; 6 String newString = Arrays.toString(knights.split(" ")); 7 System.out.println(newString); 8 }
3.replaceFirst()和replaceAll()方法
示例:替換knights字元串中所有母音字母為下劃線
1 public static void test(){ 2 String knights = 3 "Then, when you have found the shrubbery," 4 + "you must cut down the mightiest tree in the forest... " 5 + "with... a herring"; 6 String newKnights = knights.replaceAll("[AaEeIiOoUu]", "_"); 7 System.out.println(newKnights); 8 }
replaceFirst()方法只在首次出現時替換,replaceAll則替換所有滿足條件的部分