下面是直接的答案。我保持簡短,因爲如果不理解正則表達式,它們就沒有意義。這種理解最好通過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