Java正则表达式(1)
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则替换所有满足条件的部分