Regular expression for matching non-negative integers in PHP?

It seems to me that it works with the following regular expression preg_match() :

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

And yet it is strange that it corresponds to -0 , given that - generally not allowed in regular expression. Why?

What's even weirder if you switch parts divided by | :

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

Matches all negative integers such as -2 and -10 , etc.

What am I missing here? Is there a better regular expression for a non-negative integer?

+7
php regex
source share
1 answer

Your regular expression: @^(?:[1-9][0-9]*)| 0$@ @^(?:[1-9][0-9]*)| 0$@

  • says that they correspond to those numbers that begin with 1-9 , followed by any digit 0 or more OR
  • correspond to those numbers that end in 0 .

Clearly, -0 satisfies condition 2, so you get a match.

The regular expression you need: @^(?:[1-9][0-9]*|0) $@

which matches 0 or any other +ve number without a leading 0 . If leading 0 is enabled, all you need to check is that the input contains numbers for which you can use: ^\d+$ , as Mark points out.

Also, why not just do a simple check:

 if($input >= 0) // $input is non -ve. 
+6
source share

All Articles