您可以在一個單一的正則表達式與幾個lookahead assertions做到這一點(在.net中):如果所有條件都滿足
^(?=.*\p{Lu})(?:.*\p{Ll})(?=.*\d)(?=.*\W)(?!.*(.).*\1.*\1)
將匹配。
^ # Match the start of the string
(?=.*\p{Lu}) # True if there is at least one uppercase letter ahead
(?=.*\p{Ll}) # True if there is at least one lowercase letter ahead
(?=.*\d) # True if there is at least one digit ahead
(?=.*\W) # True if there is at least one non-alnum character ahead
(?!.*(.).*\1.*\1) # True if there is no character repeated twice ahead
注意,比賽是不會消耗字符串的任何字符 - 如果你想匹配操作返回你對匹配的字符串,在正則表達式的末尾添加.*
。
在JavaScript中,您不能使用Unicode字符屬性。因此,您可以使用
^(?=.*[A-Z])(?:.*[a-z])(?=.*\d)(?=.*\W)(?!.*(.).*\1.*\1)
這當然只會使用ASCII字母進行驗證。如果這對你沒問題,沒問題。你可以去擴充像[A-ZÄÖÜÀÈÌÒÙÁÉÍÓÚ]
等字符類,但你可能永遠不會完成這個。在服務器端,如果你想驗證產生相同的結果,你必須指定RegexOptions.ECMAScript
,所以.NET正則表達式引擎的行爲就像JavaScript引擎(感謝Alan Moore注意!)。
我很難讓這個模式在Rubular上工作:http://rubular.com/r/008s20R3fa – 2011-01-25 08:54:50