Why does this regex fail?

I have a password check script in PHP that checks for several different regular expressions and produces a unique error message, depending on which one fails. Here is an array of regular expressions and error messages that are raised if the match fails:

array(
    'rule1' => array(
        '/^.*[\d].*$/i',
        'Password must contain at least one number.'
    ),
    'rule2' => array(
        '/^.*[a-z].*$/i',
        'Password must contain at least one lowercase letter'
    ),
    'rule3' => array(
        '/^.*[A-Z].*$/i',
        'Password must contain at least one uppercase letter'
    ),
    'rule4' => array(
        '/^.*[~!@#$%^&*()_+=].*$/i',
        'Password must contain at least one special character [~!@#$%^&*()_+=]'
    )
);

For some reason, no matter what I went through the test, the "Special Characters" rule fails. I assume this is an expression problem. If there is a better (or correct) way to spell these expressions, I'm all ears!

+3
source share
3 answers

, :

/^.*[A-Z].*$/i

i PCRE_CASELESS, . i.

+6

:

/[~!@#$%^&*()_+=]/

. .

, , , - .

, , /i

+1

( rubular.com):

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*()_+=]).*

This uses lookahead (which is supported by PHP functions pregsince they are PCRE) instead of matching all the different rules. I'm not sure why yours is not working.

References

0
source

Source: https://habr.com/ru/post/1749427/


All Articles