最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript Regular Expression for Password - Stack Overflow

programmeradmin1浏览0评论

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 e in ANY order?

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 e in ANY order?

Share Improve this question edited Jun 21, 2010 at 21:01 Roddy 68.2k45 gold badges171 silver badges281 bronze badges asked Jun 21, 2010 at 15:09 atlantisatlantis 8371 gold badge10 silver badges16 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 3

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 prised the lookahead.

发布评论

评论列表(0)

  1. 暂无评论