8

It seems I'm stuck again with a simple regex.

What I'd like:

  • A number between 1 and 999
  • Optional: a comma , sign
  • If the comma sign is entered, minimum 1 decimal and maximum 3 decimals should be presebt.

Allowed:
100
999,0
999,999
999,99

Disallowed:
-1
0
999,
999,9999

This is what I have so far:

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

Any tips?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Bv202
  • 3,924
  • 13
  • 46
  • 80
  • This is pretty much the same, it can be adapted trivially for your needs: http://stackoverflow.com/questions/26901088/regex-numbers-between-xx-xxx-xx – Qantas 94 Heavy Jun 05 '15 at 08:42

2 Answers2

8

You can use this regex:

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

RegEx Demo

Main difference from OP's regex is use of [1-9] which matches digits 1 to 9 before rest of the regex.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    I'd love it if people actually explained what their regex does. – evolutionxbox Jun 05 '15 at 08:46
  • Hmm, weird. In your demo, it seems to work correctly. Still, when using this, it accepts a comma with no decimals and when decimals are present, the validation fails :s – Bv202 Jun 05 '15 at 08:49
  • I'm using Angular, using the ng-pattern directive: ng-pattern="/^[1-9]\d{0,2}(?:\,\d{1,3})?$/" – Bv202 Jun 05 '15 at 08:54
  • For some reason, even numbers like 9999,99999999 are accepted with this regex, while your demo clearly shows it shouild not. Very weird, but thanks for the help already! – Bv202 Jun 05 '15 at 08:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79750/discussion-between-bv202-and-anubhava). – Bv202 Jun 05 '15 at 09:00
7

This regex should work :

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

Here is the explanation :

^[1-9]: It should begin with a number between 1 and 9

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

(?:,: Followed by a comma

\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

Michel Antoine
  • 632
  • 7
  • 20