regexdecimal

regex with range decimal positive and negative number


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 ...


Solution

  • 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.