本篇来学习正则表达式里面的数量词的表示方法,顾名思义,数量词就描述匹配多少个个数的意思。
1.API中数量词的定义
2.代码分别测试每个数量词
package regex;
public class Demo1_Regex {
/*
* X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次
*/
public static void main(String[] args) {
//demo1();
//demo2();
//demo3();
//demo4();
//demo5();
demo6();
}
public static void demo6() {
String regex = "[abc]{2,5}"; // 至少2次,最多5次
System.out.println("a".matches(regex)); // 匹配1次
System.out.println("ab".matches(regex)); // 匹配2次
System.out.println("abab".matches(regex)); // 匹配4次
System.out.println("ababc".matches(regex)); // 匹配5次
System.out.println("abcabc".matches(regex)); // 匹配6次
}
public static void demo5() {
String regex = "[abc]{2,}"; // 至少2次
System.out.println("a".matches(regex)); // 匹配1次
System.out.println("ab".matches(regex)); // 匹配2次
System.out.println("abc".matches(regex)); // 匹配3次
System.out.println("abbcde".matches(regex)); // 匹配4次,但是de是范围外字符
System.out.println("ababccab".matches(regex)); // 匹配8次
}
public static void demo4() {
String regex = "[abc]{3}"; // 恰好3次
System.out.println("a".matches(regex)); // 匹配1次
System.out.println("ab".matches(regex)); // 匹配2次
System.out.println("abc".matches(regex)); // 匹配3次
System.out.println("aaa".matches(regex)); // 匹配3次
System.out.println("cbc".matches(regex)); // 匹配3次
}
public static void demo3() {
String regex = "[abc]+"; //表示1到多次
System.out.println("a".matches(regex)); // 匹配1次
System.out.println("ab".matches(regex)); // 匹配a b各1次
System.out.println("aabbcc".matches(regex));
System.out.println("ab".matches(regex));
System.out.println("".matches(regex)); // 0次匹配不行,只是一次
}
public static void demo2() {
String regex = "[abc]*"; //*表示0到多次
System.out.println("a".matches(regex)); // 匹配1次
System.out.println("b".matches(regex)); // 匹配1次
System.out.println("d".matches(regex)); // a b c范围之外
System.out.println("c".matches(regex)); // 匹配1次
System.out.println("".matches(regex)); // 匹配0次
}
public static void demo1() {
String regex = "[abc]?"; //表示匹配a b c一次或者没有
System.out.println("a".matches(regex));
System.out.println("b".matches(regex));
System.out.println("c".matches(regex));
System.out.println("d".matches(regex)); // d在a b c范围之外
System.out.println("".matches(regex)); // 一次也没有
}
}