需要正则表达式来满足密码要求
我需要一个正则表达式来测试以下用户密码:
必须至少包含 8 个字符,采用字母数字格式,不超过 4 个连续数字,密码中没有 id(即不能使用:1234
、9876
、abcd
或 1234abvc
)
我正在使用 ^([a-zA-Z0-9!@#$*%]{ 8,15})$
目前效果很好,但不考虑连续的字符片段。我不知道如何将其添加到混合中。
任何帮助都会很棒!
I need a regex to test a users password for the following:
Must be minimum 8 characters with alphanumeric format, no more than 4 consecutive numbers, no id in the password (i.e. cannot use: 1234
, 9876
, abcd
, or 1234abvc
)
I am using ^([a-zA-Z0-9!@#$*%]{8,15})$
currently and it works great, but doesn't account for the consecutive characters piece. I'm not sure how to add that to the mix.
Any help would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不能代表所有人,但我更愿意看到这个而不是正则表达式:
如果您想让调用者知道为什么密码不被接受,您可以返回一个
枚举
类型或抛出异常。我更喜欢enum
方法。I can't speak for everyone, but I would prefer to see this instead of a regex:
If you want to let the caller know why the password is not accepted, you can return an
enum
type or throw exceptions. I 'd prefer theenum
approach.使用(注释)正则表达式可以轻松完成:
Easily done with a (commented) regex:
如果你想用正则表达式解决它,只需添加一个否定的前瞻断言。您可以在此处测试它
添加的部分
(?!.*\d{4,}.*)
不会消耗你的字符串,它只是检查连续是否有 4 个或更多数字,如果有,则为 false。为什么要将密码限制为 15 个字符?我在我的例子中删除了这个。
If you want to solve it with regex, just add an negative lookahead assertion. You can test it here
The added part
(?!.*\d{4,}.*)
does not consume your string, it just checks if there are 4 or more numbers in a row and if so, its false.Why do you want to limit the passwords to 15 characters? I removed this in my example.
使用多个正则表达式来实现特定规则比将它们全部合并到一个字符串中要容易得多。
考虑到这一点,这种正则表达式会导致连续的失败:
It would be far easier to use multiple regular expressions that implement a specific rule than to meld them all into one string.
With that in mind, the consecutives would fail with this sort of regex: