Javascript Regular Expression for Password
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:
/(?=.*[A-Z])(?=.*[!@#\$%])/
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:
/(?=[^A-Z]*[A-Z])(?=[^!@#\$%]*[!@#\$%])/
On passwords of usual lengths the time difference probably won't be easily measurable, though.
The ?=
is called a lookahead where it will scan the rest of the string to see if the match is found. Normally, regex go character by character, but the ?=
tells it to "lookahead" to see if it exists.
There is also a negative lookahead of ?!
.
the "?=" does this. It is a "Positive Lookahead"
From JavaScript Regular Expression Syntax
Positive lookahead matches the search string at any point where a string matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
精彩评论