regex question: not allow a single dot (allow only if have digit before dot or digit after dot)

Viewed 275

I would like to allow user to type the following decimal or integer values (A)

.5
0.500
3
0
0.0
30
500000
4000.22
0.

This is the following regex that I have used:

factor: /^-?\d*[.]??\d*$/,

But the problem is that the above regex also allow the following invalid number (B)

        . (comment: a single dot )
       00.5 (multiple zeros before dot)
      0000.5
       00 (multiple zeros)

Also not allow user type negative values i.e. -3, -0.5

I am trying to modify the above regex to not allow the invalid values at (B), but allows the values at (A)

My attempt which does not work:

 factor: /^-?\d*[.]+\d*$/, 
4 Answers

Try the following regex:

^-?[1-9]*?0?(\.\d+)?$

Example Demo

You could match an optional hyphen and then assert that the string does not start with 2 zeroes.

Then match optional digits, an optional dot and match 1+ digits to prevent matching an empty string.

^-?(?!00)\d*\.?\d+$
  • ^ Start of string
  • -? Match optional -
  • (?!00) Negative lookahead, assert not 2 zeroes directly to the right
  • \d* Match 0+ digits
  • \.? Match optional .
  • \d+ Match 1+ digits
  • $ End of string

Regex demo

const regex = /^-?(?!00)\d*\.?\d+$/;
[
  ".5",
  "0.500",
  "3",
  "0",
  "0.0",
  "30",
  "500000",
  "4000.22",
  ".",
  "00.5",
  "0000.5",
  "00",
  "-4000",
  "-0",
  "-00",
  ".",
  ", ",
  "00.4"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));

you can make use of following expression which evaluates dot on the basis of digits before dot.

^-?(((?!00)\d+(?:\.{1}\d*)*)|((?!00)\d*(?:\.{1}\d+)))?$

Demo link

try this regex ^-?[1-9]*\.?\d+$

the brackets say that you can have 0 or 1 digit.

Related