String regex doesn't work

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

  • more than 10 characters
  • must have at least one lowercase character
  • must have at least one top level character
  • Must have either a number or a special character

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

Why is this not working?

its adoption is abcdefgh123 but not abcdefgh&+

+4
source share
5 answers

Personally, I would do a separate length check, and then one check for each of the character’s requirements. I do not like to use too complex regular expressions when something can be done in a more readable way.

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

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

Also, you do not need .* Twice in your regular expression and can use .{10,} as the main expression, so this should be the same:

  ^ (? =. * [ 0-9@ # $% ^ & + =]) (? =. * [az]) (? =. * [AZ]). {10,} $
+3
source

I think you just need extra steam around the number or symbol bit.

^.*(?=.{10,})(?=.*([0-9]|[@#$%^&+=]))(?=.*[az])(?=.*[AZ]).*$

http://regexr.com?2srhm

+1
source

If you need a solution for the code, an alternative could be:

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

Please note that these features include Unicode characters. What is surprising for the password. If this is a problem, you can 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))) { } 
+1
source

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

Expanded:

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

Edit - added 0-9, skipped this requirement

0
source

Source: https://habr.com/ru/post/1334544/


All Articles