Regex does not recognize underscores as special characters

/(?=^.{8,}$)(?=.*[ _!@ #$%^&*-])(?=.*\d)(?=.*\W+)(?![.\n])(?=.*[az])(?=.*[AZ]).*$/ 

I am trying to make a regular expression for checking the password so that the password must be at least 8 characters long and contain one uppercase, one lowercase, one number and one special char. It works great, but does not recognize the underscore (_) as a special character. Ie, Pa $$ w0rd, but Pass_w0rd does not. Thoughts?

+4
source share
4 answers

This part of the regex seems to look for special characters:

 (?=.*[ !@ #$%^&*-]) 

Note that the character class does not contain underscores, try changing this to the following:

 (?=.*[ _!@ #$%^&*-]) 

You will also need to modify or delete this part of the regular expression:

 (?=.*\W+) 

\W equivalent to [^a-zA-Z0-9_] , so if the underscore is your only special character, this part of the regular expression will crash. Instead, change it to the following (or delete it, it will be superfluous, since you already check for special characters before):

 (?=.*[^\w_]) 

Full regex:

 /(?=^.{8,}$)(?=.*[ _!@ #$%^&*-])(?=.*\d)(?=.*[^\w_])(?![.\n])(?=.*[az])(?=.*[AZ]).*$/ 
+3
source

This one also works. It defines a special character, excluding alphanumeric characters and spaces, so it includes an underscore:

 (?=.*?[AZ])(?=.*?[az])(?=.*?[\d])(?=.*?[^\sa-zA-Z0-9]).{8,} 
+1
source

The problem is that the only thing that \W can satisfy by definition is something other than [a-zA-Z0-9_] . The underscore does not specifically match \W , and in Pass_w0rd nothing compares to it.

I suspect that having your special list of special characters and \W is redundant. Choose one and you will probably be happier. I also recommend dividing all this into several separate tests for much better maintainability.

0
source

A simpler regex that works for you is this:

 /(?=.*[ _!@ #$%^&*-])(?=.*\d)(?!.*[.\n])(?=.*[az])(?=.*[AZ])^.{8,}$/ 

There were several errors in the original regular expression, for example:

  • You do not need to use lookahead to provide 8 character input
  • negative lookahead [.\n] missing .*
  • (?=.*\W+) is redundant and probably serves no purpose
0
source

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


All Articles