字符类(匹配单个字符)
| 语法 | 作用 |
|---|
| [abc] | 匹配a,b,c这三个中的一个字符 |
| [^abc] | 匹配 除了a,b,c之外的任何字符 |
| [a-zA-Z] | 匹配a到z,A到Z的字符 |
| [a-d[m-p]] | 匹配a到d,或者m到p之间的单个字符 |
| [a-z&&[def]] | 匹配a-d和def的交集,单个字符 |
public class Demo1 {
public static void main(String[] args) {
System.out.println("abc".matches("[abc]"));
System.out.println("a".matches("[abc]"));
System.out.println("--------------------");
System.out.println("a".matches("[^abc]"));
System.out.println("d".matches("[^abc]"));
System.out.println("--------------------");
System.out.println("我".matches("[a-zA-Z]"));
System.out.println("A".matches("[a-zA-Z]"));
System.out.println("--------------------");
System.out.println("e".matches("[a-d[m-p]]"));
System.out.println("b".matches("[a-d[m-p]]"));
System.out.println("--------------------");
System.out.println("a".matches("[a-z&&[def]]"));
System.out.println("f".matches("[a-z&&[def]]"));
System.out.println("--------------------");
}
}
预定义字符(匹配单个字符)
| 语法 | 作用 |
|---|
| .(符号点) | 任意单个字符 |
| \d | 一个数字[0-9] |
| \D | 匹配一个非数字 [^0-9] |
| \s | 匹配一个空格字符 |
| \S | 匹配一个非空格字符 [^\s] |
| \w | 匹配一个字符数字下划线字符 [a-zA-Z_0-9] |
| \W | 匹配一个非字母数字下划线字符 [^\w] |
public class Demo2 {
public static void main(String[] args) {
System.out.println("我".matches("."));
System.out.println("h".matches("."));
System.out.println("--------------------");
System.out.println("a".matches("\\d"));
System.out.println("1".matches("\\d"));
System.out.println("--------------------");
System.out.println("4".matches("\\D"));
System.out.println("爱".matches("\\D"));
System.out.println("--------------------");
System.out.println("h".matches("\\s"));
System.out.println(" ".matches("\\s"));
System.out.println("--------------------");
System.out.println(" ".matches("\\S"));
System.out.println("1".matches("\\S"));
System.out.println("--------------------");
System.out.println("中".matches("\\w"));
System.out.println("a".matches("\\w"));
System.out.println("--------------------");
System.out.println("_".matches("\\W"));
System.out.println("国".matches("\\W"));
}
}
数量词
| 语法 | 作用 |
|---|
| x? | 表示x出现一次或0次 |
| x* | 表示x出现0次或多次 |
| x+ | 表示x出现1次或多次 |
| x{n} | 表示x正好出现n次 |
| x{n,} | 表示x至少出现n次 |
| x{n,m} | 表示x至少出现n次不超过m次 |
public class Demo3 {
public static void main(String[] args) {
System.out.println("xx".matches("x?"));
System.out.println("x".matches("x?"));
System.out.println("--------------------");
System.out.println("abc".matches("x*"));
System.out.println("xxxxx".matches("x*"));
System.out.println("--------------------");
System.out.println("".matches("x+"));
System.out.println("x".matches("x+"));
System.out.println("--------------------");
System.out.println("xx".matches("x{3}"));
System.out.println("xxx".matches("x{3}"));
System.out.println("--------------------");
System.out.println("x".matches("x{2,}"));
System.out.println("xxx".matches("x{2,}"));
System.out.println("--------------------");
System.out.println("xx".matches("x{3,5}"));
System.out.println("xxxx".matches("x{3,5}"));
}
}