javascript - Regex for a number which can starts with 0 -




i use regex field:

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

what want allow user enter 0 beginning of number, in cas, must enter @ least second digit diffrent 0 , same rule applied third , fourth digits.

example:

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

in short, 0 value must not allowed. how can using regex? or better if javascript script?

if want match numbers have 1 4 digits in part before decimal separator, , 2 digits after decimal separator (i deduce regex used) and not start 00 (that requirement comes verbal explanation), use

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

see regex demo.

details

  • ^- start of string
  • (?!00) - no 2 0s @ start of string
  • (?!0+(?:[.,]0+)?$) - negative lookahead fails match if there 1 or more 0s, followed optional sequence of . or , followed 1 or more zeros string end
  • \d{1,4} - 1 4 digits
  • (?:[.,]\d{1,2})? - 1 or 0 occurrences of
    • [.,] - . or ,
    • \d{1,2} - 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})?$/;  (var s of ss) {   var result = rx.test(s);   console.log(s, "=>", result);  }





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -