简体   繁体   English

密码的Javascript正则表达式

[英]Javascript Regular Expression for Password

I am writing the regex for validating password in Javascript. 我正在编写用于验证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: 以下正则表达式(由Gumbo建议)效率更高,因为它避免了不必要的回溯:

/(?=[^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 JavaScript正则表达式语法

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". 例如,“ Windows(?= 95 | 98 | NT | 2000)”与“ Windows 2000”中的“ Windows”匹配,而与“ Windows 3.1”中的“ Windows”匹配。 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. 前瞻不消耗字符,也就是说,在匹配发生之后,对下一个匹配的搜索将在上一个匹配之后立即开始,而不是在组成先行的字符之后开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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