I am writing the regex for validating password in Javascript. The constraints are:
- Password must contain at least one uppercase character
- Password must contain at least a special character
With trial and error and some searching on the net, I found that this works:
/(?=.*[A-Z]+)(?=.*[!@#\$%]+)/
Can someone please explain the part of this expression which mentions that the uppercase letter and special character can come in ANY order?
I think this would work even better:
Look-arounds do not consume characters, therefore, start for the second look-ahead is the same as for the first. Which makes checks for those two characters independent of each other. You could swap them around and resulting regex would still be equivalent to this.
The following regex (suggested by Gumbo) is slightly more efficient, as it avoids unnecessary backtracking:
On passwords of usual lengths the time difference probably won’t be easily measurable, though.