請正則表達式高手給出更好的解決方案
1. 必須8位到15位。
2.至少包含如何四組中的三組。
(1) 包含a-z
(2) 包含A-Z
(3) 包含0-9
(4) 包含特殊字符:@#$%
本人對正則表達式也是懵懵懂懂,只能像如下比較弱弱的實現,請正則表達式高手給出更好的解決方案,當然其他方式也歡迎!











































靜靜等候中..........................
posted on 2009-07-22 22:16 advincenting 閱讀(1458) 評論(11) 編輯 收藏
快樂生活 !
posted on 2009-07-22 22:16 advincenting 閱讀(1458) 評論(11) 編輯 收藏
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PasswordTest {
private final static Matcher passwordMatcher = Pattern.compile(
"^(?:([a-z])|([A-Z])|([0-9])|([@#$%])){8,15}$"
).matcher("");
public static void main(String[] args) {
String[] strs = {
"abcdefg12345",
"aaabbbAAA$$$",
"aaabbbAAAa@13434",
"aaAA11",
"AAAaaa113@"
};
for(int i = 0; i < strs.length; i++) {
System.out.printf("str: %-20s length: %2d result: %s%n",
strs[i],
strs[i].length(),
checkPassword(strs[i])
);
}
}
public static boolean checkPassword(String password) {
if (password == null) {
return false;
}
passwordMatcher.reset(password);
if (!passwordMatcher.matches()) {
return false;
}
int count = 0;
for (int i = passwordMatcher.groupCount(); i > 0; i--) {
if (passwordMatcher.start(i) > -1) {
count++;
}
}
return (count >= 3);
}
}
長度Check:
[a-zA-Z0-9@#$%]{8,15}
有效性Check:
([a-z]+[A-Z]+[0-9]+)|
([A-Z]+[0-9]+[@#$%]+)|
([a-z]+[0-9]+[@#$%]+)|
([a-z]+[A-Z]+[@#$%]+)
使用前請好好測試一下兒! 回復 更多評論
@菜菜寶寶
aaaZXXXXCCCC
好像這個字符串也可以被匹配上吧!
這和LZ的要求不太符合! 回復 更多評論
@游客
您好,aaaZXXXXCCCC 這個的匹配結果返回的是 false 啊。 回復 更多評論
^((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[@#$%])|(?=.*\d)(?=.*[a-z])(?=.*[@#$%])|(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$%]))[0-9a-zA-Z@#$%]{8,15}$ 回復 更多評論
@xing.liu
@菜菜寶寶
999999@LLL 不匹配
----------------------------------
999999@LLL 我測試的結果是 true 啊?符合博主的要求。 回復 更多評論
只有注冊用戶登錄后才能發表評論。 | ||
![]() |
||
網站導航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
|
||