2010-10-29 89 views
2

我似乎無法得到此工作。C#正則表達式

我正在尋找一個正則表達式來驗證密碼。允許的字符是a-zA-Z0-9,但序列必須至少有1個數字和1個大寫字母。

可以這樣做嗎?

+0

可能重複http://stackoverflow.com/questions/2582079/help-with-password-complexity -regex) – 2010-10-29 20:36:11

回答

2
^(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]+$ 

應該做的。

^    # start of string 
(?=.*[A-Z]) # assert that there is at least one capital letter ahead 
(?=.*[0-9]) # assert that there is at least one digit ahead 
[A-Za-z0-9]+ # match any number of allowed characters 
       # Use {8,} instead of + to require a minimum length of 8 characters. 
$    # end of string 
0

您可以在正則表達式中使用non-zero-width lookahead/lookbehind assertions。例如:

^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$ 

要求存在至少一個數字,一個小寫字母和一個大寫字母。使用\w可以讓您接受非英文或重音字符(您可能希望或不希望允許)。否則,請使用[a-zA-Z]。

+0

這比OP想要的要多得多('\ w'是.NET中的Unicode-aware) - 儘管當然限制有效字母爲*密碼*也沒有多大意義。 – 2010-10-29 20:37:56

+0

@Tim Pietzcker:是的,我知道。我提到'\ w'將接受來自unicode集的重音和國際字符。這是使用[a-zA-Z]構造的替代方案。 – LBushkin 2010-10-29 20:39:42

+0

對不起,我沒有仔細閱讀你的答案。但是'\ w'也匹配數字和下劃線(以及其他的「連續標點符號」字符)。 – 2010-10-29 20:44:49

0
bool valid = 
    Regex.IsMatch(password, @"\w+")// add additional allowable characters here 
    && Regex.IsMatch(password, @"\d") 
    && Regex.IsMatch(password, @"\p{Lu}"); 
[求助與密碼複雜性的正則表達式(的