skip to Main Content

I’m trying have regex with the following requirements:

  • can contain any characters (symbols, spaces) except @ symbol
  • but should contains at least 7 digits, but no more than 20 digits

Should not match:

1234 
abxz1234 
a1b2c3 d 
12345678901234567890123456789 
@123456789
1234@56789 

Should match:

1234567890   
123. 45678
$sb w77 123456789
((12345. 678
123 456 789
(333) 444-77.33 ext 4422

2

Answers


  1. How about using [^@] and then a simple range on the character length {7,20}, ie

    php > $pattern = '/^[^@]{7,20}$/';
    php > var_dump(preg_match($pattern, '123456789012345678901'));
    int(0)
    php > var_dump(preg_match($pattern, '12345678901234567890'));
    int(1)
    php > var_dump(preg_match($pattern, '1234567890123456789'));
    int(1)
    php > var_dump(preg_match($pattern, '1234567890123@56789'));
    int(0)
    
    Login or Signup to reply.
  2. You can use ^[^d@]*(?:d[^d@]*){7,20}$.

    • ^ is the start-of-input assertion.
    • $ is the end-of-input assertion.
    • [^d@]* matches any sequence of characters that does not include a digit nor @
    • d matches one digit.
    • (?: ) is a (non-capturing) group so we can add a quantifier to it
    • {7,20} is the quantifier that requires the preceding pattern to repeat at least 7 times and at most 20.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search