生成字母+数字6位字符串

package test;

import java.util.Random;
import java.util.regex.Pattern;

public class CodeUtil {

    public static final char[] CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
            'G', 'H', 'I', 'G', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

    public static String generateCode() {
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 6; i++) { // 生成六个字符
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        String result = buffer.toString();
        if(Pattern.matches("[\d]{6}", result) || Pattern.matches("[\D]{6}", result)){
            return generateCode();
        }else{
            return result;
        }
    }
}
原文地址:https://www.cnblogs.com/zno2/p/4972382.html