0

I have a regex expression in order to test my password : at least one digit, at least one upper letter,at least one lower letter and at least one special character.

/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s])/

But underscore is not recognized as special character.

How can I improve this ?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128

1 Answers1

5

The problem here is that, for JavaScript, \w represents:

[a-zA-Z0-9_]

So you are avoiding _ implicitly.

Explaination

This part of your regex:

(?=.*?[^\w\s]) // Match special character

Is equivalent to:

(?=.*?[^a-zA-Z0-9_\s])

Bibliography

The \w metacharacter is used to find a word character.

A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.

https://www.w3schools.com/jsref/jsref_regexp_wordchar.asp

Community
  • 1
  • 1
lilezek
  • 6,976
  • 1
  • 27
  • 45
  • I mean underscore is not a part of `special character`. – Mihai Alexandru-Ionut Nov 08 '17 at 14:34
  • @Alexandru-IonutMihai The problem is that you are doing `[^\w\s]` which is equivalent to `[^a-zA-Z0-9_\s]`. So, the definition of _special character_ is not a letter, not a number, not space and not an underscore. – lilezek Nov 08 '17 at 14:35