Java REGEX – Regular Expression Numeric Ranges Validation

Prerequisites

Development environment

  1. JDK 1.8 Downloads
  2. Eclipse Mars Download

Here’re some examples of common numeric ranges:

  • 000..255: ^([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$
  • 0 or 000..255: ^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$
  • 0 or 000..127: ^(0?[0-9]?[0-9]|1[01][0-9]|12[0-7])$
  • 0..999: ^([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$
  • 000..999: ^[0-9]{3}$
  • 0 or 000..999: ^[0-9]{1,3}$
  • 1..999: ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$
  • 001..999: ^(00[1-9]|0[1-9][0-9]|[1-9][0-9][0-9])$
  • 1 or 001..999: ^(0{0,2}[1-9]|0?[1-9][0-9]|[1-9][0-9][0-9])$
  • 0 or 00..59: ^[0-5]?[0-9]$
  • 0 or 000..366: ^(0?[0-9]?[0-9]|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-6])$

Let’s me break down the regex for the range 0-255.

  • The regex [0-9] matches single-digit numbers 0 to 9
  • [1-9][0-9] matches double-digit numbers 10 to 99.
  • 1[0-9][0-9] matches 100 to 199.
  • 2[0-4][0-9] matches 200 through 249.
  • 25[0-5] adds 250 till 255.

And we got [0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]

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