Maximum 3 digits, up to 3 decimal places

I seem to be stuck again with a simple regex.

What I need:

  • Number from 1 to 999
  • Optional: comma, sign
  • If a comma is entered, a minimum of 1 decimal and a maximum of 3 decimal places must be preceded.

Allowed:
one hundred
999.0
999999
999.99

Invalid:
-one
0
999,
999,9999

This is what I still have:

^[0-9]{1,3}(?:\,[0-9]{1,3})?$ 

Any tips?

+7
javascript regex
source share
2 answers

You can use this regex:

 /^[1-9]\d{0,2}(?:\,\d{1,3})?$/ 

RegEx Demo

The main difference from the OP regular expression is the use of [1-9] , which matches the numbers 1 to 9 before the rest of the regular expression.

+4
source share

This regex should work:

 ^[1-9]\d{0,2}(?:,\d{1,3})?$ 

Here is an explanation:

^[1-9] : it must begin with a number from 1 to 9

\d{0,2} : followed by a minimum of 0, a maximum of 2 digits (0-9)

(?:, : after the decimal point

\d{1,3})? : IF there is a comma, it should be followed by one to three digits

$ : End of line

EXAMPLE

Thanks @ dev-null for this link: Explanation

+5
source share

All Articles