密碼至少包含 1 個大寫 1 個小寫 1 個數字 1 個特殊字元,長度至少為 10
由於字元/數字可以在字串中的任何位置,我們需要前瞻。前瞻是 zero width
意味著他們不消耗任何字串。簡單來說,在每個先行條件滿足後,檢查的位置重置到原始位置。
假設 : - 將非單詞字元視為特殊字元
^(?=.{10,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W).*$
在繼續解釋之前,讓我們來看看字串 1$d%aA
上的正規表示式如何工作( 這裡不考慮長度 )
圖片來源 : - https://regex101.com/
值得注意的事情
- 由於錨標記
^
,從字串的開頭開始檢查。 - 在前瞻條件滿足後,檢查位置被重置為啟動。
正規表示式細分
^ #Starting of string
(?=.{10,}$) #Check there is at least 10 characters in the string.
#As this is lookahead the position of checking will reset to starting again
(?=.*[a-z]) #Check if there is at least one lowercase in string.
#As this is lookahead the position of checking will reset to starting again
(?=.*[A-Z]) #Check if there is at least one uppercase in string.
#As this is lookahead the position of checking will reset to starting again
(?=.*[0-9]) #Check if there is at least one digit in string.
#As this is lookahead the position of checking will reset to starting again
(?=.*\W) #Check if there is at least one special character in string.
#As this is lookahead the position of checking will reset to starting again
.*$ #Capture the entire string if all the condition of lookahead is met. This is not required if only validation is needed
我們也可以使用上面的正規表示式的非貪婪版本
^(?=.{10,}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?\W).*$