Search code examples
regexregex-lookaroundsregex-groupregex-greedy

Max length ignoring one character in Regex


I have a Regex Which allows up to 6 decimals("." is the decimal separator)

/^\d*[.]?\d{0,6}$/

I also want to put max length condition so that user can only enter 12 digits and max length should exclude "." how do I do that with Regex.


Solution

  • You could use a positive lookahead to check for either a number with a decimal place with up to 6 digits after it or a string of 12 digits) and then match up to 13 characters in total:

    ^(?=\d*\.\d{0,6}$|\d{1,12}$).{1,13}$
    

    For this input, the 2nd and 5th values will match:

    1234567890123
    123456.789012
    12345.6789012
    1234567.890123
    12345.67890
    

    Demo on regex101