Regex up to 4-digit number and/or up to 4 decimal places

Viewed 553

I need a regex that allows UP TO 4 digit number AND/OR 4 decimal places.

ONLY allowed format examples (I'm just using only 1s to make the format looks simple, it all should be [0-9])

1 
1.1
1.11
1.111
1.1111
11
11.1
11.11
11.111
11.1111
111
111.1
111.11
111.111
111.1111
1111
1111.1
1111.11
1111.111
1111.1111

So far the closest one I've gotten --

"^[0-9]{0,4}(?:.[0-9]{0,4}$)"

It works pretty good when I enter numbers + decimals. However, if I just enter numbers without decimals, I can enter 4+ number digits, which it should not.

1 Answers

The ^[0-9]{0,4}(?:.[0-9]{0,4}$) only seems to be almost working for you. As . is unescaped, it matches any char including digits, and you have an impression it works.

Once you properly escape . with a literal \, it will stop "working", because this will require a dot.

You need to use

/^\d{0,4}(?:\.\d{0,4})?$/
"^[0-9]{0,4}(?:[.][0-9]{0,4})?$"

Details:

  • ^ - start of string
  • [0-9]{0,4} / \d{4} - zero to four digits
  • (?:\.[0-9]{0,4})? - an optional occurrence of a . and then zero to four digits
  • $ - end of string.
Related