CodesJava

Easy learning with example program codes

Java Regex Quantifiers


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

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.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
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki