gpt4 book ai didi

Java - 密码的正则表达式

转载 作者:行者123 更新时间:2023-11-29 06:42:10 25 4
gpt4 key购买 nike

我如何构造一个正则表达式,使我正在制作的密码字段包含至少一个数字、至少一个小写字母和至少一个大写字母,其中顺序无关紧要并且这些字符之间可以有任何内容?

我试过这个并得到了类似的东西:".*\\d.*[a-z].*[A-Z].*"但这要求数字在前,小写字母在后,大写字母在后。

最佳答案

您的用例不是正则表达式特别擅长的用例之一——如果您受困于正则表达式,我想您别无选择,只能列举 6 种情况:

.*[0-9].*[a-z].*[A-Z].*|.*[0-9].*[A-Z].*[a-z].*|.*[a-z] ... | ...

检查实际的 java 代码会更容易(并且更具可读性):

String  password = "";
boolean complies = password.matches(".*[0-9].*")
&& password.matches(".*[a-z].*")
&& password.matches(".*[A-Z].*");

或(更丑陋,但可能更快):

boolean complies = false;
{
boolean hasDigit = false;
boolean hasLowercase = false;
boolean hasUppercase = false;
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
hasDigit |= '0' <= c && c <= '9';
hasLowercase |= 'a' <= c && c <= 'z';
hasUppercase |= 'A' <= c && c <= 'Z';
if (hasDigit && hasLowercase && hasUppercase) {
complies = true;
break;
}
}
}

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

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