質問

I want to check if password contains:

  • minimum 2 lower cases
  • minimum 1 upper case
  • minimum 2 selected special characters

The problem is that when i want to verify this,it admits two lowercases,but only if they are consecutive,like this:paSWORD . if I enter pASWORd,it returns an error.

This is the code

preg_match("/^(?=.*[a-z]{2})(?=.*[A-Z])(?=.*[_|!|@|#|$|%|^|&|*]{2}).+$/")

I don't see where the problem is and how to fix it.

役に立ちましたか?

解決

You're looking for [a-z]{2} in your regex. That is two consecutive lowercases!

I will go out on a limb and suggest that it is probably better to individually check each of your three conditions in separate regexes rather than trying to be clever and do it in one.

I've put some extra braces in which may get your original idea to work for non-consecutive lowercase/special chars, but I think the expression is overcomplex.

preg_match("/^(?=(.*[a-z]){2})(?=.*[A-Z])(?=(.*[_!@#$%^&*]){2}).+$/")

他のヒント

You can use this pattern to check the three rules:

preg_match("/(?=.*[a-z].*[a-z])(?=.*[A-Z])(?=.*[_!@#$%^&*].*[_!@#$%^&*])/");

but if you want to allow only letters and these special characters, you must add:

preg_match("/^(?=.*[a-z].*[a-z])(?=.*[A-Z])(?=.*[_!@#$%^&*].*[_!@#$%^&*])[a-zA-Z_!@#%^&*]+$/");

a way without regex

$str = '*MauriceAimeLeJambon*';

$chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%^&*';
$state = array('lower' => 2, 'upper' => 1, 'special' => 2);
$strlength = strlen($str);

for ($i=0; $i<$strlength; $i++) {
    $pos = strpos($chars, $str[$i]);
    if (is_numeric($pos)) {
        if     ($state['lower'] && $pos<26) $state['lower']--;
        elseif ($state['upper'] && $pos<52) $state['upper']--;
        elseif ($state['special']) $state['special']--;
    } else { $res = false; break; }
    $res = !$state['lower'] && !$state['upper'] && !$state['special'];
}

var_dump($res);

(This version give the same result than the second pattern. If you want the same result than the first pattern, just remove the else {} and put the last line out of the for loop.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top