String类的三个内建正则表达式工具:
1.matches()方法
示例:检查一个句子是否以大写字母开头,以句号结尾
public static boolean checkFormat(String sentence){
return sentence.matches("^[A-Z].+\\.$");
}
2.split()方法
示例:以空格分割knights字符串并以数组形式返回
public static void test(){
String knights =
"Then, when you have found the shrubbery,"
+ "you must cut down the mightiest tree in the forest... "
+ "with... a herring";
String newString = Arrays.toString(knights.split(" "));
System.out.println(newString);
}
3.replaceFirst()和replaceAll()方法
示例:替换knights字符串中所有元音字母为下划线
public static void test(){
String knights =
"Then, when you have found the shrubbery,"
+ "you must cut down the mightiest tree in the forest... "
+ "with... a herring";
String newKnights = knights.replaceAll("[AaEeIiOoUu]", "_");
System.out.println(newKnights);
}
replaceFirst()方法只在首次出现时替换,replaceAll则替换所有满足条件的部分