如何验证密码至少包含一个大写或小写字母?

How can I validate a password to contain at least one upper-case or lower-case letter?

条件

  1. 密码长度 >=8 且 <=15
  2. 一个数字(0-9),一个字母(A-Z或a-z),一个特殊字符(@#$*!)

我试过了

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,15})

但这会同时检查小写和大写,但我需要其中一个。

俗话说:"I had a problem, so I thought of using a regex. Now I have two problems".

一个好的ol'方法没有错。

public bool IsPasswordValid(string password)
{
    return password.Length >= 8 &&
           password.Length <= 15 &&
           password.Any(char.IsDigit) &&
           password.Any(char.IsLetter) &&
           (password.Any(char.IsSymbol) || password.Any(char.IsPunctuation)) ;
}

根据 this:

,这是一个包含所有允许的特殊符号的正则表达式
((?=.*\d)(?=.*[a-zA-Z])(?=.*[@!-'()\+--\/:\?\[-`{}~]).{8,15})

只需删除 A-Z 匹配组并使用 RegexOptions.IgnoreCase 声明正则表达式以忽略大小写(即,提供的字母是大写、小写还是两者都无关紧要;a-z 组仍会匹配它们):

new Regex(@"((?=.*\d)(?=.*[a-z])(?=.*[@#$%]).{8,15})", RegexOptions.IgnoreCase)