我正在学习正则表达式,我发现了一个关于使用它们进行密码输入验证的有趣且有用的页面 here .我的问题是关于以下表达式中的 .*
:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
我知道 .*
是一个代表任意数量文本(或无文本)的通配符,但我在这些前瞻表达式中无法理解它的用途。为什么需要这些才能使这些前瞻功能按需发挥作用?
先行意味着直接先行。所以如果你写:
(?=a)
这意味着第一个字符应该是a
。有时,例如密码检查,您不希望这样。你想表达某处应该有一个a
。所以:
(?=.*a)
表示第一个字符可以是 b
、8
或 @
。但最终某处应该有一个 a
。
因此,您的正则表达式意味着:
^ # start a match at the beginning of the string
(?=.*[a-z]) # should contain at least one a-z character
(?=.*[A-Z]) # should contain at least one A-Z character
(?=.*\d) # should contain at least one digit
[a-zA-Z\d]{8,} # consists out of 8 or more characters and only A-Za-z0-9
$ # end the match at the end of the string
如果没有 .*
,就永远不会匹配,因为:
"^(?=[a-z])(?=[A-Z])(?=\d)[a-zA-Z\d]{8,}$"
意思是:
^ # start a match at the beginning of the string
(?=[a-z]) # first character should be an a-z character
(?=[A-Z]) # first character should be an A-Z character
(?=\d) # first character should be a digit
[a-zA-Z\d]{8,} # consists out of 8 or more characters and only A-Za-z0-9
$ # end the match at the end of the string
因为不存在既是A-Z字符又是数字的字符。这永远不会满足。
旁注:
- 我们不在前瞻中捕获,所以贪婪无关紧要;
- 点
.
默认为 not match the new line character ;
- 即使您有一个约束
^[A-Za-z0-9]{8,}$
也意味着您只会验证没有新行的输入。<
我是一名优秀的程序员,十分优秀!