Home > front end >  regex with range decimal positive and negative number
regex with range decimal positive and negative number

Time:07-18

How to allow user to put negative, positive and decimal number with range with regex?

I use the (/^[- ]?[0-9]\d{0,5}(\.\d )?$/) regex below it works with positive and negative number but to range decimal number for maximum number 6, it doesn't work.

how i can do that? Exemple : if i put the number 123456789 : for standard formats it should be 123456 for positive number it should be 123456 for negative number it should be -123456 for decimal number it should be 12.3456 or 1.23456 or 123.456 ...

CodePudding user response:

How about using a negative lookahead after first digit to limit max length:

^[- ]?\d(?!.{7})\d{0,5}(?:\.\d )?$

See the demo on regex101

The lookahead (?!.{7}) fails if there are more than six characters after it.

CodePudding user response:

I dont think there is a nice solution. You could do something ugly with negative and positive lookahead:

^[ -]?((?!.*\..*\.)(?=.*\.)\d[\d.]{0,5}\d|\d{1,6})$
  • (?!.*\..*\.) makes sure there are not 2 dots
  • (?=.*\.) makes sure there is a dot (otherwise we can match 7 digits)
  • \d[\d.]{0,5}\d makes sure the dot is not at start or end

CodePudding user response:

If you want to limit the decimal numbers up to 6, you will not need the $ sign.

Also, if you already use \d, then [0-9] is useless.

Your mistake is also \d . You don't want to match all digits, do you? So instead of , you will need a quantifier.

So this should be the regex that you want:

^[- ]?\d{1,6}(\.\d{1,6})?

See result: https://regex101.com/r/q8DOKR/1

  • Related