题目:随机产生字符串,字符串中的字符只能由特殊字符 (!@#$%), 大写字母(A-Z),小写字母(a-z)以及数字(0-9)组成,且每种字符至少出现一次。
这样产生字符串的方式可以应用到如下场景,比如,我们有一个应用就是添加用户完毕之后,发邮件给指定用户包括一个长度为11位的初始化密码。
1. 我们先来定义一个包含这四种字符类型的char数组
private static final char[] symbols;
static {
StringBuilder tmp = new StringBuilder();
for (char ch = '0'; ch <= '9'; ++ch)
tmp.append(ch);
for (char ch = 'a'; ch <= 'z'; ++ch)
tmp.append(ch);
for (char ch = 'A'; ch <= 'Z'; ++ch)
tmp.append(ch);
// 添加一些特殊字符
tmp.append("!@#$%");
symbols = tmp.toString().toCharArray();
}
详细代码如下
import java.util.Random;
public class RandomAlphaNumericGenerator {
private static final char[] symbols;
static {
StringBuilder tmp = new StringBuilder();
for (char ch = '0'; ch <= '9'; ++ch)
tmp.append(ch);
for (char ch = 'a'; ch <= 'z'; ++ch)
tmp.append(ch);
for (char ch = 'A'; ch <= 'Z'; ++ch)
tmp.append(ch);
// 添加一些特殊字符
tmp.append("!@#$%");
symbols = tmp.toString().toCharArray();
}
private final Random random = new Random();
private final char[] buf;
public RandomAlphaNumericGenerator(int length) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}
2. 根据步骤1中产生的字符数组,随机产生一个字符串,判断其是否至少包含一个特殊字符、一个数字、一个小写字母以及一个大写字母,如果不是,则重新产生一个新的随机字符串直到产生符合条件的随机字符串为止
在这里,我们使用正则表达式的方式验证字符串是否符合要求,正则表达式为.*(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%]).*
测试代码如下:
public class RandomAlphaNumericGeneratorTest {
public static void main(String[] args) {
RandomAlphaNumericGenerator randomTest = new RandomAlphaNumericGenerator(11);
for(int i=0;i<10;i++){
String result = null;
do {
result = randomTest.nextString();
} while (!result.matches(".*(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%]).*"));
System.out.println(result);
}
System.out.println();
}
}
某一次运行的结果如下:
u7YMTR4!o$! H004vVb!W9Z RLnhzUpYl6$ @UFDysu7qBa %2edSPri$e2 KY9!HPtcWlX ciVns$DMIN9 j6BU%heDIHp Nmn8747#$Vd oLp@DDUxH8d
本文原文地址http://thecodesample.com/?p=935
更多实例 请访问 http://thecodesample.com/