Search code examples
javascriptregexng-pattern

Regex for a number which can starts with 0


I use this regex for my field:

/^([1-9]([0-9]){0,3}?)((\.|\,)\d{1,2})?$/;

What I want to do is to allow the user to enter 0 as a beginning of the number, but in this cas, he must enter at least a second digit diffrent from 0 and the same rule is applied for the third and fourth digits.

Example:

  • 01 -> valid
  • 00 -> not valid
  • 0 -> not valid
  • 1 -> valid

In short, zero value must not be allowed. How can I do this using Regex? or would it be better if I just do it with a javascript script?


Solution

  • If you want to only match numbers that have 1 to 4 digits in the part before a decimal separator, and up to 2 digits after the decimal separator (I deduce it from the regex you used) and that do not start with 00 (that requirement comes from your verbal explanation), use

    /^(?!00)(?!0+(?:[.,]0+)?$)\d{1,~4}(?:[.,]\d{1,2})?$/
    

    See the regex demo.

    Details

    • ^- start of string
    • (?!00) - no two 0s at the start of the string
    • (?!0+(?:[.,]0+)?$) - a negative lookahead that fails the match if there are one or more 0s, followed with an optional sequence of . or , followed with one or more zeros up to the string end
    • \d{1,4} - any 1 to 4 digits
    • (?:[.,]\d{1,2})? - 1 or 0 occurrences of
      • [.,] - a . or ,
      • \d{1,2} - any 1 or 2 digits
    • $ - end of string.

    JS demo:

    var ss = ['1','1.1','01','01.3','023.45','0','00','0.0','0.00','0001'];
    var rx = /^(?!00)(?!0+(?:[.,]0+)?$)\d{1,4}(?:[.,]\d{1,2})?$/;
    for (var s of ss) {
     var result = rx.test(s);
     console.log(s, "=>", result);
    }