Tuz
Tuz

Reputation: 1980

Regex for no more than 5 digits or contain string

I looking for a regex that returns true if string include characters or only 5 digits or include a string for php

tried this ^\D{0,5}$

but it's not working

for examples:

12345 - return true
1234455667&&&% . - true

123456 -false 
1234 - true 
FFGF - true 
empty string - true 

Upvotes: 1

Views: 2503

Answers (3)

Sweeper
Sweeper

Reputation: 271575

If I understood you correctly. You want true if any of the following is true:

  • contains no more than 5 digits
  • empty string
  • contains at least non-digit

We can use | to separate these three conditions.

^(?:\d{0,5}|.*?\D.*)$

Note that the empty string case is also matched by \d{0,5}

Upvotes: 2

revo
revo

Reputation: 48711

PHP code (test online):

$str = '1234';
if (preg_match('~^(?(?=\d+$)\d{1,5}|.*)$~', $str)) {
    // true
}

If you are telling digits shouldn't be 5 or more you should build paths for them. One way is using conditional construct which PCRE has a support for (?()...):

^(?(?=\d+$)\d{1,5}|.*)$

Live demo

Breakdown:

  • ^ Match beginning of input string
  • (? Start of conditional
    • (?=\d+$) Positive lookahead, if digits only
    • \d{1,5} It should be at most five characters long
    • | Otherwise
    • .* Match any thing else
  • ) End of construct
  • $ Match end of input string

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may match a string that consists of 1 to 4 digits, or is empty, or is not all digits:

if (preg_match('~^(\d{1,5}|(?!\d+$).*)$~', $v)) {
    return true;
}

See the regex demo. Details:

  • ^ - start of string
  • ( - start of a grouping construct matching...
    • \d{1,5} - 1 to 5 digits
    • | - or
    • (?!\d+$).* - any 0+ chars (other than line break chars, add s modifier to make it match strings with line breaks) as many as possible, but not equal to all digits
  • ) - end of the grouping construct
  • $ - end of string.

See PHP demo:

$strs = ['12345', '1234455667&&&% .', '123456', '1234', ''];

foreach ($strs as $v) {
    if (preg_match('~^(\d{1,5}|(?!\d+$).*)$~', $v)) {
        echo "$v: true\n";
    } else {
        echo "$v: false\n";
    }
}

Output:

12345: true
1234455667&&&% .: true
123456: false
1234: true
: true

Upvotes: 1

Related Questions