regex - How to understand a particular regular expression pattern?
问题描述
I found this regex online but I am struggling to understand it. It is this:
(?=^.{6,10}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{":;'?/>.<,])(?!.*\s).*$
http://regexlib.com/Search.aspx?k=password&c=-1&m=5&ps=100
The description is:
This regular expression match can be used for validating strong password. It expects at least 1 small-case letter, 1 Capital letter, 1 digit, 1 special character and the length should be between 6-10 characters. The sequence of the characters is not important. This expression follows the above 4 norms specified by Microsoft for a strong password.
I see there are the following groups. I have read that ?=
means look ahead.
(?=^.{6,10}$)
Does this means looks ahead that there should be 6-10 characters?(?=.*\d)
Does this mean that look ahead that there should be 0 or more characters followed by a digit (so at least one digit)?. Could this have been written as(?=\d+)
meaning there should be at least 1 digit?(?=.*[a-z])
pattern to matcha-z
. Again, could this have been written as(?=[a-z]+)
?(?=.*[A-Z])
pattern to matchA-Z
. Again, could this have been written as(?=[A-Z]+)
?(?=.*[!@#$%^&*()_+}{":;'?/>.<,])
Is.*
not required here as well?(?!.*\s).*$
- what does this mean?
解决方案
你对第一组是正确的。因为它在开头和结尾都用^
and锚定$
,所以它必须匹配整个输入。所以它要求有6-10个字符。
接下来的四个前瞻需要.*
在开始时匹配输入中任何位置所需的字符类型。如果您只是编写(?=\d+)
它,则必须匹配输入中当前位置的数字,即开头。通过为它们中的每一个加上前缀.*
,它允许不同的类型(数字、小写、大写、标点符号)以任何顺序排列。你不需要+
在它后面加上,因为匹配一次就足够了。
(?!.*\s)
是负前瞻。\s
匹配空格,因此这意味着字符串不能包含任何空格。
最后,.*$
只匹配整个输入。这只是在所有的前瞻之后有一些东西所需要的。
推荐阅读
- python - xattr 出现问题,“没有名为 'pkg_resources' 的模块”
- java - 如何使用 DateTimeFormatter 实现以下模式?
- mysql - mysql - 失败无法启动
- sql - 如何连接具有别名 PLSQL 的两列
- java - 在 JavaFX 中的 TableCell 内的 ImageView 上单击事件
- python - 使用带有输入作为参数的函数时出现 TypeError
- python - 有没有办法使用 Python 将数据保存在命名的 Excel 单元格中?
- html - 我使用“img”标签添加了一个徽标。这导致我的嵌入式网站下拉不再滚动。我使用 iframe 标记嵌入其他网站
- css - 在具有 css 样式的文本字符串下绘制箭头线
- java - Appium 报错 packageAndLaunchActivityFromManifest failed