In this article, we will learn the representation of quantifiers in regular expressions. As the name suggests, quantifiers describe the meaning of how many numbers to match.
1. Definition of quantifiers in API
2. The code tests each quantifier separately
package regex; public class Demo1_Regex { /* * X? X, once or not at all X* X, zero or more times X+X, one or more times X{n} X, exactly n times X{n,} X, at least n times X{n,m} X, at least n times, but not more than m times */ public static void main(String[] args) { //demo1(); //demo2(); //demo3(); //demo4(); //demo5(); demo6(); } public static void demo6() { String regex = "[abc]{2,5}"; // at least 2 times, at most 5 times System.out.println("a".matches(regex)); // match 1 time System.out.println("ab".matches(regex)); // match 2 times System.out.println("abab".matches(regex)); // match 4 times System.out.println("ababc".matches(regex)); // match 5 times System.out.println("abcabc".matches(regex)); // match 6 times } public static void demo5() { String regex = "[abc]{2,}"; // at least 2 times System.out.println("a".matches(regex)); // match 1 time System.out.println("ab".matches(regex)); // match 2 times System.out.println("abc".matches(regex)); // match 3 times System.out.println("abbcde".matches(regex)); // matches 4 times, but de is an out-of-range character System.out.println("ababccab".matches(regex)); // match 8 times } public static void demo4() { String regex = "[abc]{3}"; // exactly 3 times System.out.println("a".matches(regex)); // match 1 time System.out.println("ab".matches(regex)); // match 2 times System.out.println("abc".matches(regex)); // match 3 times System.out.println("aaa".matches(regex)); // match 3 times System.out.println("cbc".matches(regex)); // match 3 times } public static void demo3() { String regex = "[abc]+"; //represents 1 or more times System.out.println("a".matches(regex)); // match 1 time System.out.println("ab".matches(regex)); // match ab once each System.out.println("aabbcc".matches(regex)); System.out.println("ab".matches(regex)); System.out.println("".matches(regex)); // 0 matches won't work, just once } public static void demo2() { String regex = "[abc]*"; //* means 0 or more times System.out.println("a".matches(regex)); // match 1 time System.out.println("b".matches(regex)); // match 1 time System.out.println("d".matches(regex)); // outside the scope of abc System.out.println("c".matches(regex)); // match 1 time System.out.println("".matches(regex)); // match 0 times } public static void demo1() { String regex = "[abc]?"; //Indicates matching abc once or not 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 is outside the scope of abc System.out.println("".matches(regex)); // not once } }