I seem to get it to work with the following regexp by preg_match():
@^(?:[1-9][0-9]*)|0$@
Yet it's weird that it matches -0, considering there are no - allowed at all in the regexp. Why?
What's more weird is that if you switch the parts divided by |:
@^0|(?:[1-9][0-9]*)$@
It matches all negative integers such as -2 and -10开发者_StackOverflow中文版, etc.
What am I missing here? Any better regexp for non-negative integer?
Your regex: @^(?:[1-9][0-9]*)|0$@
- says match those number that start
with 1-9followed by any digit0or more times OR
- match those numbers that end with 0.
Clearly -0 satisfies condition 2 so you get the match.
The regex you need is: @^(?:[1-9][0-9]*|0)$@
which matches 0 or any other +ve number without leading 0. If leading 0's are allowed then all you need to check is if the input contains digits for which you can use: ^\d+$ as Mark mentions.
Also why not just do a simple check like:
if($input >= 0)
 // $input is non -ve.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论