前面一篇了解了字符类,这篇来学习预定义字符类。没什么好说的,先每个字符类都写一个正则表达式来测试下,通过举例一些正向和反向的例子来练习。反正一开始,用得少记不住每个字符的含义,后面用多了,自然就会写正则表达式。
1. 在API文档关于预定义字符类
上面同样是用来匹配单个字符的
2. 代码练习
针对没个字符类写一个方法来测试
package regex;
public class Demo1_Regex {
public static void main(String[] args) {
//demo1();
//demo2();
//demo3();
//demo4();
//demo5();
//demo6();
demo7();
}
public static void demo7() {
String regex = "\\W"; // 表示非单词字符,就是标点符号
System.out.println("\n".matches(regex));
System.out.println("&".matches(regex));
System.out.println("#".matches(regex));
System.out.println("a".matches(regex));
System.out.println("9".matches(regex));
}
public static void demo6() {
String regex = "\\w"; // 表示单词字符:[a-zA-Z_0-9]
System.out.println("\n".matches(regex));
System.out.println("a".matches(regex));
System.out.println("H".matches(regex));
System.out.println("i".matches(regex));
System.out.println("Z".matches(regex));
System.out.println("9".matches(regex));
}
public static void demo5() {
String regex = "\\S"; // 表示非空白字符
System.out.println("\t".matches(regex));
System.out.println("a".matches(regex));
}
public static void demo4() {
String regex = "\\s"; // 表示空白字符
System.out.println("\t".matches(regex)); // 制表符
System.out.println("\f".matches(regex));
System.out.println("\n".matches(regex)); //回车并换行
System.out.println("\r".matches(regex)); // 回车符
}
public static void demo3() {
String regex = "\\D"; // 表示非数字,注意单个\表示转译字符
System.out.println("a".matches(regex));
System.out.println("你".matches(regex));
System.out.println("&".matches(regex));
System.out.println("7".matches(regex));
}
public static void demo2() {
String regex = "\\d"; // 表示数字0-9,注意单个\表示转译字符,所以这里需要\\d
System.out.println("0".matches(regex));
System.out.println("9".matches(regex));
System.out.println("10".matches(regex));
}
public static void demo1() {
String regex = ".";
System.out.println("a".matches(regex));
System.out.println("a".matches(regex));
System.out.println("ab".matches(regex));
String regex2 = "..";
System.out.println("ab".matches(regex2));
}
}