Java Regex Quantifiers

Java Regex Quantifiers

The quantifiers specify how often an element can occur. The symbols ?, *, + and {} define the quantity of the regular expressions.
 

Regex Description
X? X occurs once or not at all
X+ X occurs once or more times
X* X occurs zero or more times
X{n} X occurs n times only
X{n,} X occurs n or more times
X{y,z} X occurs at least y times but less than z times

Java Regex Quantifiers Example

package com.w3schools;
 
import java.util.regex.Pattern;
 
public class RegexTest {
	public static void main(String args[]){
		System.out.println("? quantifier ....");  
		//true (a or j or n comes one time) 
		System.out.println(Pattern.matches("[ajn]?", "a")); 
		//false (a comes more than one time) 
		System.out.println(Pattern.matches("[ajn]?", "aaa")); 
		//false (a j and n comes more than one time)
		System.out.println(Pattern.matches("[ajn]?", "aammmnn"));  
		//false (a comes more than one time)
		System.out.println(Pattern.matches("[ajn]?", "aazzta"));  
		//false (a or j or n must come one time) 
		System.out.println(Pattern.matches("[ajn]?", "aj")); 
 
		System.out.println("+ quantifier ....");  
		//true (a or j or n once or more times)  
		System.out.println(Pattern.matches("[ajn]+", "a"));
		//true (a comes more than one time) 
		System.out.println(Pattern.matches("[ajn]+", "aaa")); 
		//true (a or j or n comes more than once)  
		System.out.println(Pattern.matches("[ajn]+", "aammmnn"));
		//false (z and t are not matching pattern)
		System.out.println(Pattern.matches("[ajn]+", "aazzta"));  
 
		System.out.println("* quantifier ....");  
		//true (a or j or n may come zero or more times) 
		System.out.println(Pattern.matches("[ajn]*", "ajjjna")); 
	}
}

Output

? quantifier ....
true
false
false
false
false
+ quantifier ....
true
true
false
false
* quantifier ....
true