Skip to content

Instantly share code, notes, and snippets.

@chenzhenjia
Created August 2, 2017 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenzhenjia/ef625e67825f13762ef2bffeda5ce5ad to your computer and use it in GitHub Desktop.
Save chenzhenjia/ef625e67825f13762ef2bffeda5ce5ad to your computer and use it in GitHub Desktop.
生成随机密码
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