Bilal
Bilal

Reputation: 23

Regular expression for non negative integers including 0

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.

Upvotes: 0

Views: 117

Answers (2)

The fourth bird
The fourth bird

Reputation: 163277

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]*)$

Regex demo

Or if a non capture group is not supported

^(0|[1-9][0-9]*)$

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195418

Try (regex101):

^(?!0\d+)\d+

Which evaluates:

111  - True
0    - True
013  - False 
120  - True

Upvotes: 1

Related Questions