ptheofan
ptheofan

Reputation: 2270

PHP Regex - accept all positive numbers except for 1

Regexes and I have a relationship of love and hate. I need to match (accept) all numbers except for number 1 and 0. Seeing it as math and not string, number >= 2 should be matched. Also please consider this is part of a Zend route param (reqs) so I have to go with regex unless I want to extend Route class, and etc. etc. :)

103 => 103
013 => 013
201 => 201
340 => 340
111 => 111
001 => no match
010 => 010
100 => 100
  1 => no match
000 => no match
 00 => no match
  0 => no match

I've tried some variations of [^1][|\d+] (trying to nail one digit at a time :D) but so far I've failed horribly :(

Nailed it!!

The regex I was looking for appears to be the following

^([2-9]|[2-9]\d|[1-9]\d{1,})$

Upvotes: 1

Views: 278

Answers (5)

ptheofan
ptheofan

Reputation: 2270

The following regex will match any number (not digits, but number as a whole) >= 2

^([2-9]|[2-9]\d|[1-9]\d{1,})$

Thanks for all the valuable help in the answers, some were really helpful and helped me reach the desired result.

Upvotes: 0

Jon
Jon

Reputation: 437336

Just use negative lookahead to exclude patterns with all zeroes that optionally end in an one:

/^(?!0*1?$)\d+$/

If you read it without the parens, this regex matches anything that consists of one or more decimal digits. The parens contain an assertion that causes the regex to match only if the pattern 0*1?$ cannot be matched beginning at the start of the input, so this removes the scenario of all zeroes and one with any number of prepended zeroes.

Upvotes: 6

wushijia
wushijia

Reputation: 1

//if the numbers only include  0 or 1 reurn false;else will return the numbers
function match_number($number){
    if(preg_match("/^[01]*$/", $number) > 0){
        return false;
    } else {
        return $number;
    }
 }

Upvotes: 0

exussum
exussum

Reputation: 18550

Your thinking of it the wrong way.

^[01]+$

will match all that onyl contain 0 or 1.

If that matches reject it, if it doesnt match check its a valid number and you should have a match

Upvotes: 0

justhalf
justhalf

Reputation: 9107

Use negation on the result for matching all zeroes and ones

if(!preg_match("^[01]+$",$string)) {...}

Upvotes: 2

Related Questions