//正则表达式 就是一个字符串 但能表示某一类的字符串或者规则
//字符串也是一个正则表达式 但只能表达自己
String string = "";
string.matches("[]"); //引用方式,string的matches方法
//[]表示单个字符
//[abc]:a或者b或者c中的一个
//[^abc]:除了a、b、c以外的任何单个字符
//[a-zA-Z]:a~z和A~Z中的任意单个字符
// . 表示任意字符,\\.表示一个确定的.字符串
// \d 表示数字字符
// \D 表示非数字字符
// \s 表示空格字符
// \S 表示非空格字符
// \w [a-zA-Z0-9_]
// \W 表示除了\w以外的所有字符
//数量修饰
//无论是字符类型还是预定义字符类型都只能表示单个的字符,无法表示0个字符,
//也无法表示多个字符。需要使用一个数量词来修饰字符的个数。
//放在字符后面或者[]后面
//X? 表示X这个字符,出现0次或者1次
//X+ 表示X这个字符,出现1次或者多次
//X* 表示X这个字符,出现0次、1次或者多次
//X{n} 表示X这个字符,恰好出现n次
//X{n,} 表示X这个字符,至少出现n次
//X{n, m}表示X这个字符,至少出现n次,最多出现m次
//和正则表达式有关的String中的三个方法
//boolean matches(String regex):判断当前字符串是否和参数正则表达式匹配
//String[] split(String regex):使用指定的正则表达式切割当前字符串
//String replaceAll(String regex, String replacement):将调用者字符串中的所有匹配regex正则的子串,全都替换成replacement新串
有关正则的几个案例
特定号码验证
Scanner reader = new Scanner(System.in);
System.out.println("Input the number: ");
String string = reader.nextLine();
if (string.matches("[1-9][0-9]{4,14}")) { //matches 正则的使用
System.out.println("Legal");
}else {
System.out.println("Ilegal");
}
//test ZHENZE //字符串中单字匹配
System.out.println("c".matches("[abc]")); //是否含有[]中的一个 单字的范围
System.out.println("*".matches("[^abc]")); //除abc以外的所有
System.out.println("5".matches("[a-zA-Z0-9]")); //是否在三个范围中
//单字匹配
System.out.println("3".matches("\\.")); //单反斜杠表转义 本来只需要单反斜杠+ . 现在需要写两个反斜杠 \.
System.out.println("r".matches(".")); //都可以匹配 (单个任意)
System.out.println("4".matches("\\d")); //匹配数字 \d
System.out.println("r".matches("\\D")); //匹配非数字 \D
System.out.println(" ".matches("\\s")); //匹配空格 \s
System.out.println(" ".matches("\\S")); //匹配非空格 \S
System.out.println("s".matches("\\w")); //匹配数字字母下划线 \w
System.out.println("r".matches("\\W")); //匹配非数字字母下划线 \W /. /s /w /d /S /D /W .
//匹配出现次数
System.out.println("as".matches("[a-z]{2}"));//匹配2次 精确匹配 {}修饰前面单字匹配的次数
System.out.println("as".matches("[a-z]{2-5}"));//匹配2-5次
System.out.println("as".matches("[a-z]{2,}"));//匹配至少2次 若字符串长度不够匹配次数 则出错
//模糊匹配
System.out.println("as".matches("[a-z]?"));//匹配0或1次
System.out.println("as".matches("[a-z]+"));//匹配1到多次
System.out.println("asss".matches("[a-z]*"));//匹配0,1,或多次 全部 []{} []? []+ []*
//正则表达式相关的三个方法 split matches replaceAll
String s1 = "awd,wfa,fbdb,ki,kklbcv,ac,ascnm,cyu";
String[] arr = s1.split(",");
System.out.println(Arrays.toString(arr));
String s2 = "fef7ef9a fefefuwef7g6weg9wfwef8wev";
String[] arr2 = s2.split("\\d");
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]+" ");
}
System.out.println();
String s3 = "daw87dawd98w6daw8d675f5s46fgm35hj42,j2k3g54fd8";
String arr3 = s3.replaceAll("\\d+", "00");
System.out.println(arr3);
有待更新