下面是直接的答案。我保持简短,因为如果不理解正则表达式,它们就没有意义。这种理解最好通过regular-expressions.info获得。我建议你也尝试一下列出的regex helper tools,它们让你可以进行实验 - 在编辑模式时看到实时捕捉/匹配,非常有帮助。
1:插入符^
是锚,它的意思是“干草堆/串/行的开始”。
- 如果脱字符是字符类
[]
中的第一个符号,它具有不同的含义:它否定该类。 (所以在[^ab]
插入符号,使该类比赛的任何事物不 AB)
2:点.
和星号*
有两个不同的用途:
- 的点匹配任何单个字符除了换行
\n
。
- 星号表示“允许零个或许多前面的类型”。
当这两者合并为.*
它基本上读取“零或更多任何东西,直到换行符或另一个规则生效”。
7:美元$
也是一个类似插入符号的锚点,具有相反的功能:“干草堆的结束”。
编辑:
简单括号()
周围的东西使它成为组。在这里你有(?=)
这是一个断言,特别是一个积极向前看断言。它所做的就是检查干草堆中当前光标位置是否存在实际存在的内容。还在我这儿?
例如:foo(?=bar)
匹配foo
只有后跟bar
。 bar
从不匹配,只返回foo
。记住
利用这一点,让我们来分析你的正则表达式:
/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/
Reads as:
^.* From Start, capture 0-many of any character
(?=.{4,}) if there are at least 4 of anything following this
(?=.*[0-9]) if there is: 0-many of any, ending with an integer following
(?=.*[a-z]) if there is: 0-many of any, ending with a lowercase letter following
(?=.*[A-Z]) if there is: 0-many of any, ending with an uppercase letter following
.*$ 0-many of anything preceding the End
你说的密码字符的顺序事 - 它确实没有在我的测试。见下面的测试脚本。希望这个清理了一两件事。如果你正在寻找另一个正则表达式是更宽容一点,看到regex password validation
<pre>
<?php
// Only the last 3 fail, as they should. You claim the first does not work?
$subjects = array("aaB1", "Baa1", "1Baa", "1aaB", "aa1B", "aa11", "aaBB", "aB1");
foreach($subjects as $s)
{
$res = preg_match("/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $s, $matches);
echo "result: ";
print_r($res);
echo "<br>";
print_r($matches);
echo "<hr>";
}
优秀的在线工具检查和测试正则表达式: https://regex101.com/
Search Google for Reg Ex教程 – 2012-04-18 01:00:18
与您的实际问题无关,但强制人们对密码过于复杂的模式可能会导致他们只是将其写入某处 - 从而消除了密码的安全性。 – jprofitt 2012-04-18 01:04:52
由于您正在标记此PHP:http://php.net/manual/en/book.pcre.php – 2012-04-18 04:47:10