CodesJava

Easy learning with example program codes

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.
 

RegexDescription
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.codesjava;
 
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
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status