package com_04_21;
//正则表达式(regular expression)
public class Demo01 {
public static void main(String[] args) {
//从String类中的matches方法开始。乍一看,matches方法和equals方法非常相似。
System.out.println("Java".matches("Java"));
System.out.println( "Java".equals("Java"));
//但是,matches方法的功能更强大。它不仅可以匹配固定的字符串,还能匹配一组遵循从某种模式的字符串
boolean x = "Java is fun".matches("Java.*");
boolean y = "Java is fool".matches("Java.*");
boolean z = "Java is powerful".matches("Java.*");
System.out.println(x + "" + y + z);
//在前面语句中的"Java.*"是一个正则表达式。它描述的字符串模式是以字符串Java开始的,后面紧跟任意0个或多个字符。这里,子串.*与0个或多个字符相匹配
System.out.println("440-02-4543".matches("\\d{3}-\\d{2}-\\d{4}"));
//这里\\d表示单个数字,\\d{3}表示三个数字。
//regex正则表达式是一个字符串
String regex = "\\d{3}-\\d{2}-\\d{4}";
System.out.println("220-10-1234".matches(regex));
//replaceAll、replaceFirst和split也可以和正则表达式结合在一起使用
String s = "a+b$#c".replaceAll("[$+#]","NNN");
System.out.println(s);
String[] tokens = "Java,C?C#,C++".split("[.,:;?]");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
}
}
package com_04_21;
public class Demo02 {
public static void main(String[] args) {
System.out.println("Java".matches("\\Dava"));
String socialSecureNumber = "[\\d]{3}-[\\d]{2}-[\\d]{4}";
System.out.println("111-22-3333".matches(socialSecureNumber));
System.out.println("11-22-3333".matches(socialSecureNumber));
String endNumber = "\\d*[02468]";
System.out.println("122".matches(endNumber));
String telephoneNumber = "\\([1-9][\\d]{2}\\) [\\d]{3}-[\\d]{4}";
System.out.println("(912) 921-2728".matches(telephoneNumber));
System.out.println("921-2728".matches(telephoneNumber));
//正则表达式中不要随意添加空格
String familyName = "[A-Z][a-zA-Z]{1,6}";
System.out.println("Smith".matches(familyName));
System.out.println("Johnabc".matches(familyName));
String flag = "[a-zA-Z_$][\\w$]";
//默认情况下,所有量词符都是贪婪的。这意味着它们会尽可能匹配最多次
System.out.println("Jaaavaaa".replaceFirst("a+","R"));
//可以通过在后面添加问好(?)来改变量词符的默认行为。量词符变成不情愿
System.out.println("Jaaavaaa".replaceFirst("a+?","R"));
}
}