简体   繁体   中英

Javascript Regular Expression for Password

I am writing the regex for validating password in Javascript. The constraints are:

  1. Password must contain at least one uppercase character
  2. 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?

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 ?! .

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 "?=" 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM