Java REGEX – Regular Expression Specify Character Occurrences

Prerequisites

Development environment

  1. JDK 1.8 Downloads
  2. Eclipse Mars Download

Quantifiers allow you to specify the number of occurrences to match against. For convenience, the three sections of the Pattern API specification describing greedy, reluctant, and possessive quantifiers are presented below:

Greedy Reluctant Possessive Meaning
X? X?? X?+ X, once or not at all
X* X*? X*+ X, zero or more times
X+ X+? X++ X, one or more times
X{n} X{n}? X{n}+ X, exactly n times
X{n,} X{n,}? X{n,}+ X, at least n times
X{n,m} X{n,m}? X{n,m}+ X, at least n but not more than m times

Step 1 Create Java Project

Launch Eclipse IDE; Create new Java Project by going to File -> New -> Others… -> Java Project. Choose any project name you want then click Finish.

Step 2 Create Java Class

Copy the code below to clipboard; Select src folder in your project; Press CTRL + V; Eclipse IDE will automatically create package & class file with the code that’s pasted from clipboard.

Step 3 Run The Application

Right click to the class; select Run As -> Java Application.

Output