PHP 正则表达式密码验证寻求解释


PHP regxp password validation seeking explanation

哟,

所以我正在学习正则表达式:-) 耶

我正在学习如何解析密码字符串,这些字符串必须至少包含 1 个大写字母和 1 个数字,并且可以在 6 到 12 个字符之间。

我对此有麻烦的理解。

$array = array("Hallo1ween23");
$match = preg_grep('%^(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])'S{6,12}$%',$array);
foreach($match as $value) {
    echo "<pre>" .$value . "<br>";
}

所以基本上我理解这些部分:

我所知道的例子:

此行%(?<=mail)man%查找以 mail 开头并以 man 结尾的单词

好吧。。

(?=[a-z]*?[A-Z])一个简单的版本,但仍然是相同的逻辑。 我不明白。

因此,如果有帮助,我将整个阵容分成 3 个。

接下来的两个我没有得到。

(?=[-_a-zA-Z0-9]*?[A-Z])
(?=[-_a-zA-Z0-9]*?[a-z])

我知道 ''s 表示空格,''s 表示非空格,但我真的不明白它在这里的目的。

(?=[-_a-zA-Z0-9]*?[0-9])'S

这是接受的最小和最大字母。

{6,12}

一些解释会很整洁。

提前感谢:-)

@Tafari

基本上这是一条线。

(?=[-_a-zA-Z0-9]*?[A-Z])

以及整个正则表达式行末尾的'S

我确实理解[-_a-zA-Z0-9]

* 表示零个或多个

?意味着我们不确定它是否存在

把它们放在一起,我失去了那个。

阅读以下内容供初学者Lookahead and Lookbehind Zero-Length Assertions...

以下断言是公认的。

(?!)  - Negative Lookahead     foo(?!bar)  matches foo when not followed by bar
(?=)  - Positive Lookahead     foo(?=bar)  matches foo when followed by bar
(?<!) - Negative Lookbehind    (?<!foo)bar matches bar when bar is preceded by foo
(?<=) - Positive Lookbehind    (?<=foo)bar matches bar when preceded by foo

接下来的两个我没有得到...

(?=                  look ahead to see if there is:
 [-_a-zA-Z0-9]*?     any character of: '-', '_', 'a' to 'z', 
                     'A' to 'Z', '0' to '9' (0 or more times)
  [A-Z]              any character of: 'A' to 'Z'
)                    end of look-ahead

(?=[-_a-zA-Z0-9]*?[a-z])相同的概念,除了您将a的任何字符与z匹配

接下来,'s匹配空格,'S匹配非空格。

(?=                  look ahead to see if there is:
 [-_a-zA-Z0-9]*?     any character of: '-', '_', 'a' to 'z',
                     'A' to 'Z', '0' to '9' (0 or more times)
 [0-9]               any character of: '0' to '9'
)                    end of look-ahead
'S                   non-whitespace (all but 'n, 'r, 't, 'f, and " ")

可识别以下量词。

*      Match 0 or more times
+      Match 1 or more times
?      Match 1 or 0 times
{n}    Match exactly n times
{n,}   Match at least n times
{n,m}  Match at least n but not more than m times

祝你好运。

您可以通过(?= ... )表达式将它们分开,这些表达式是前瞻性的。 唯一需要注意的另一件关键事情是使用?,通过搜索正则表达式贪婪可以更好地解释。

所以^(?=[-_a-zA-Z0-9]*?[A-Z])基本上读作:向前看,找到任何字母数字字符和/或连字符或下划线,直到找到至少一个大写字母。

(?=[-_a-zA-Z0-9]*?[a-z])同上: ...小写字母。

(?=[-_a-zA-Z0-9]*?[0-9])同上:...数。

转义序列'S实际上是在执行"匹配",假设前瞻已得到满足。大写'S{6,12}为:匹配长度在 6 到 12 个字符之间的任何非空格字符序列。