How can I represent non negative integers including 0 and no integer, except 0 should start by a 0 using regular expression? Example:
111 (true)|
0 (true)|
013 (false)|
120 (true)|
The regex I tried:
^(0|[1-9][0-9]?)$
This is how it's represented if 0 isn't included.
CodePudding user response:
Try (regex101):
^(?!0\d )\d
Which evaluates:
111 - True
0 - True
013 - False
120 - True
CodePudding user response:
You can change the quantifier from ?
(which matches 0 or 1 times) to *
which matches zero or more times.
Now the pattern matches either a single 0
or a digit that starts with 1-9 followed by optional digits 0-9.
^(?:0|[1-9][0-9]*)$
Or if a non capture group is not supported
^(0|[1-9][0-9]*)$