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 20
s @ start of string(?!0+(?:[.,]0+)?$)
- negative lookahead fails match if there 1 or more0
s, 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
Post a Comment