gpt4 book ai didi

php - 用于密码分级的正则表达式

转载 作者:搜寻专家 更新时间:2023-10-31 20:35:09 25 4
gpt4 key购买 nike

我正在研究对所用密码的质量进行分级的正则表达式。这个想法是,如果密码仅包含 1 个大写字符或至少 6 个大写字符,则该密码被认为是普通的。密码本身应至少包含 8 个字符。

期望的行为:

Aaaaaaaa -> 匹配

AAAAAAaa -> 匹配

AAaaaaaa -> 不匹配

我试过这样的:

(?=.*[A-Z]{1,1}|(?=.*[A-Z]{6,})).{8,}

这没有用,因为它也匹配 AAaaaaaa。问题是第一个允许 2-5 个大写字符的正面前瞻,但我不知道如何避免这种情况。

最佳答案

您应该将第一个先行限制为只需要整个 字符串中的 1 个大写字母。只需将完整的字符串模式定义为任何非大写字母后跟 1 个大写字母,然后允许任意数量的非大写字母字符

如果您计划要求连续 6 个大写字母,请使用

/^(?=[^A-Z]*[A-Z][^A-Z]*$|.*[A-Z]{6,}).{8,}$/
^^^^^^^^^^^^^^^^^^^^

参见 this regex demo

如果这6个大写字母可以分散在字符串周围,使用

/^(?=[^A-Z]*[A-Z][^A-Z]*$|(?:[^A-Z]*[A-Z]){6,}).{8,}$/
^^^^^^^^^^^^^^^^^^^^

(?:[^A-Z]*[A-Z]){6,} 搜索至少 6 次出现的 0+ 非大写字母字符后跟大写字母。参见 this regex demo .

如果需要支持Unicode,在正则末尾添加/u修饰符,将[A-Z]替换为\p{Lu}[^A-Z]\P{Lu}

此外,建议使用 \A 而不是 ^\z 而不是 $ 因为这是密码验证。

另一个基于 bobble bubble 建议的逻辑的正则表达式:

^                           # String start
(?=.{8,}$) # 8 or more characters other than a newline
(?:
[^A-Z]*[A-Z][^A-Z]* # a string with 1 uppercase letter only
| # or...
(?:[^A-Z]*[A-Z]){6} # 6 occ. of 0+ chars other than uppercase letters followed with 1 uppercase letter
.* # 0+ chars other than a newline
)
$ # string end

参见 regex demo作为 1 行:

/^(?=.{8,}$)(?:[^A-Z\n]*[A-Z][^A-Z\n]*|(?:[^A-Z\n]*[A-Z]){6}.*)$/

参见 this demo .

关于php - 用于密码分级的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37563968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com