Using regular expressions to validate a numeric range

Using regular expressions to validate a numeric range

To be clear: When a simple if statement will suffice

if(num < -2055  ||  num > 2055)  {
   throw  new IllegalArgumentException("num (" + num + ") must be between -2055 and 2055");

using regular expressions for validating numeric ranges is not recommended.

In addition, since regular expressions analyze strings, numbers must first be translated to a string before they can be tested. An exception is when the number happens to already be a string, such as when getting user input from the console.

(To ensure the string is a number to begin with, you could use org.apache.commons.lang3.math.NumberUtils#isNumber(s))

Despite this, figuring out how to validate number ranges with regular expressions is interesting and instructive.

(The links in this answer come from the Stack Overflow Regular Expressions FAQ.)

A one number range

Rule: A number must be exactly 15.

The simplest range there is. A regex to match this is


Word boundaries are necessary to avoid matching the 15 inside of 8215242.

A two number range

The rule: The number must be between 15 and 16. Here are three possible regexes:


(The groups are required for the “or”-ing, but they could be non-capturing: \b(?:15|16)\b)

A number range “mirrored” around zero

The rule: The number must be between -12 and 12.

Here is a regex for 0 through 12, positive-only:



\b(         //The beginning of a word (or number), followed by either
   \d       //   Any digit 0 through 9
|           //Or
   1[0-2]   //   A 1 followed by any digit between 0 and 2.
)\b         //The end of a word

Making this work for both negative and positive is as simple as adding an optional dash at the start:


(This assumes no inappropriate characters precede the dash.)

To forbid negative numbers, a negative lookbehind is necessary:


Leaving the lookbehind out would cause the 11 in -11 to match. (The first example in this post should have this added.)

Note: \d versus [0-9]

In order to be compatible with all regex flavors, all \d-s should be changed to [0-9]. For example, .NET considers non ASCII numbers, such as those in different languages, as legal values for \d. Except for in the last example, for brevity, it’s left as \d.

(With thanks to @TimPietzcker)

Three digits, with all but the first digit equal to zero

Rule: Must be between 0 and 400.

A possible regex:


Free spaced:

   (?<!-)          //Something not preceded by a dash
   \b(             //Word-start, followed by either
      [1-3]?       //   No digit, or the digit 1, 2, or 3
         \d{1,2}   //   Followed by one or two digits (between 0 and 9)
   |               //Or
      400          //   The number 400
   )\b             //Word-end

Another possibility that should never be used:


Final example: Four digits, mirrored around zero, that does not end with zeros.

Rule: Must be between -2055 and 2055

This is from a question on stackoverflow.



Regular expression visualization

Debuggex Demo


(             //Capture group for the entire number
   -?\b             //Optional dash, followed by a word (number) boundary
   (?:20            //Followed by "20", which is followed by one of 
         (?:5[0-5]        //50 through 55
           |                  //or
         [0-4][0-9])      //00 through 49
      |                                         //or
         1[0-9]{3}        //a one followed by any three digits
      |                                         //or
         [1-9][0-9]{0,2}  //1-9 followed by 0 through 2 of any digit
      |                                         //or
         (?<!-)0+         //one-or-more zeros *not* preceded by a dash
   )                 //end "or" non-capture group
)\b            //End number capture group, followed by a word-bound

(With thanks to PlasmaPower and Casimir et Hippolyte for the debugging assistance.)

Final note

Depending on what you are capturing, it is likely that all sub-groups should be made into non-capture groups. For example, this:


Instead of this:


Example Java implementation

  import  java.util.Scanner;
  import  java.util.regex.Matcher;
  import  java.util.regex.Pattern;
  import  org.apache.commons.lang.math.NumberUtils;
  <P>Confirm a user-input number is a valid number by reading a string an testing it is numeric before converting it to an it--this loops until a valid number is provided.</P>

  <P>{@code java UserInputNumInRangeWRegex}</P>
public class UserInputNumInRangeWRegex  {
  public static final void main(String[] ignored)  {

     int num = -1;
     boolean isNum = false;

     int iRangeMax = 2055;

     //"": Dummy string, to reuse matcher
     Matcher mtchrNumNegThrPos = Pattern.compile("(-?\\b(?:20(?:5[0-5]|[0-4][0-9])|1[0-9]{3}|[1-9][0-9]{0,2}|(?<!-)0+))\\b").matcher("");

     do  {
        System.out.print("Enter a number between -" + iRangeMax + " and " + iRangeMax + ": ");
        String strInput = (new Scanner(;
        if(!NumberUtils.isNumber(strInput))  {
           System.out.println("Not a number. Try again.");
        }  else if(!mtchrNumNegThrPos.reset(strInput).matches())  {
           System.out.println("Not in range. Try again.");
        }  else  {
           //Safe to convert
           num = Integer.parseInt(strInput);
           isNum = true;
     }  while(!isNum);

     System.out.println("Number: " + num);



[C:\java_code\]java UserInputNumInRangeWRegex
Enter a number between -2055 and 2055: tuhet
Not a number. Try again.
Enter a number between -2055 and 2055: 283837483
Not in range. Try again.
Enter a number between -2055 and 2055: -200000
Not in range. Try again.
Enter a number between -2055 and 2055: -300
Number: -300

Original answer to this stackoverflow question

This is a serious answer that fits your specifications. It is similar to @PlasmaPower’s answer.


Regular expression visualization

Debuggex Demo

Leave a Comment