开发者

String regex not working

I have the following regex in c sharp to check if supplied password is

  • more than 10 characters
  • should h开发者_如何学运维ave at least one lowercase character
  • should have at least one Uppercase character
  • Should have either a number or a special character

Regex.IsMatch(password, "^.*(?=.{10,})(?=.*[0-9]|[@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).*$")

Why wouldn't the above work?

its taking abcdefgh123 but not abcdefgh&+


Personally I'd do a separate check for the length and then one check for each of the character requirements. I don't like to use overly complicated regular expressions when things can be done in a more readable manner.

if (password.Length > 10 && 
    Regex.IsMatch(password, "[a-b]") && 
    Regex.IsMatch(password, "[A-Z]") && 
    Regex.IsMatch(password, "[0-9@#$%^&+=]"))
{
    //Valid password
}


The problem is probably in (?=.*[0-9]|[@#$%^&+=]), which means .*[0-9] OR [@#$%^&+=] - it should be .*[0-9@#$%^&+=].

Also, you don't really need .* twice in your regex, and can use .{10,} as the main expression, so this should be the same:

^(?=.*[0-9@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).{10,}$


I think you just need an additional paren around the "number or symbol" bit

^.*(?=.{10,})(?=.*([0-9]|[@#$%^&+=]))(?=.*[a-z])(?=.*[A-Z]).*$

http://regexr.com?2srhm


If you want a code solution, an alternative might be:

if (password.Length >= 10 &&
    password.Any(Char.IsLower) &&
    password.Any(Char.IsUpper) &&
    password.Any(c=>Char.IsDigit(c) || Char.IsSymbol(c)))
    {

    }

Note that these functions include Unicode characters. Which is awesome for a password. If that's a problem, you may use:

if (password.Length >= 10 &&
    password.Any(c => (c >= 'a') && (c <= 'z')) &&
    password.Any(c => (c >= 'A') && (c <= 'Z')) &&
    password.Any(c => Char.IsDigit(c) || "@#$%^&+=".Contains(c)))
{

}


This should work:
/^(?=.{10,})(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[0-9@#$%^&+=])/

Expanded:

 /^  
   (?= .{10,} )
   (?= .*[[:lower:]] )
   (?= .*[[:upper:]] )
   (?= .*[0-9@#$%^&+=] )
  /x;

Edit - added 0-9, missed that requirement

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜