2010-10-29 90 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}"); 
[求助与密码复杂性的正则表达式(的