Created
August 2, 2017 02:40
-
-
Save chenzhenjia/ef625e67825f13762ef2bffeda5ce5ad to your computer and use it in GitHub Desktop.
生成随机密码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final List<String> PWD_CHARS; | |
static { | |
PWD_CHARS = new ArrayList<String>(); | |
PWD_CHARS.add("123456789"); | |
PWD_CHARS.add("qwertyuipkjhgfdsazxcvbnm"); | |
PWD_CHARS.add("QWERTYUPLKJHGFDSAZXCVBNM"); | |
} | |
/** | |
* 返回一个字符串和字母的随机字符串 | |
* | |
* @param length 长度 | |
*/ | |
public static String randomString(int length) { | |
StringBuilder sb = new StringBuilder(); | |
Random random = new Random(); | |
int size = PWD_CHARS.size(); | |
for (int i = 0; i < length; i++) { | |
String pwdChar = PWD_CHARS.get(random.nextInt(size)); | |
sb.append(pwdChar.charAt(random.nextInt(pwdChar.length()))); | |
} | |
String result = sb.toString(); | |
return result.matches("(?![0-9]+$)(?![a-zA-Z]+$)(?![0-9a-z]+$)" + | |
"(?![0-9A-Z]+$)[0-9A-Za-z]+") | |
? result : randomString(length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment