【Java】javaで英数字をごちゃ混ぜした文字列をランダム生成する方法
アルファベットの大文字、小文字、数字を混ぜた文字列を生成したーい!
パスワード用の文字列を生成したーい!
とにかくよくわからん文字列を生成したーい!
そんなあなたが求めているなのはこんなコードでしょうか、 それともあんなコードでしょうか。
public class CodeSample { public static void main(String args[]){ // ------------------------------------------------------------------- // 基本編 ------------------------------------------------------------ // ------------------------------------------------------------------- // 3文字の数字を生成する String retNum = MyRandom.randomString(3, MyRandom.NUM); // 5文字のアルファベット(小文字)を生成する String retAlpL = MyRandom.randomString(5, MyRandom.ALPHA_L); // アルファベット(小文字 + 大文字) + 数字を混ぜた文字列を生成する String retNumAlp = MyRandom.randomString( 8, MyRandom.NUM + MyRandom.ALPHA_L + MyRandom.ALPHA_U); System.out.println("retNum[" + retNum + "]" + " retAlpL[" + retAlpL + "]" + " retNumAlp[" + retNumAlp + "]"); // ------------------------------------------------------------------- // 応用編 ------------------------------------------------------------ // ------------------------------------------------------------------- String password; // 大文字、小文字、数字がすべて1文字以上含まれている文字列を生成する while(true){ password = MyRandom.randomString( 10, MyRandom.NUM + MyRandom.ALPHA_L + MyRandom.ALPHA_U); // 正規表現を使用して期待した文字列が含まれているかをチェックする // 含まれていないものがあれば再度生成処理を呼ぶ。(例:大文字が含まれていなかった場合) if(!password.matches(".*[0-9].*") || !password.matches(".*[a-z].*") || !password.matches(".*[A-Z].*")){ continue; } break; } System.out.println("password[" + password + "]"); } public static class MyRandom { public static final String NUM = "0123456789"; public static final String ALPHA_L = "abcdefghijklmnopqrstuvwxyz"; public static final String ALPHA_U = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static String randomString(int count, String base){ String result = ""; java.util.Random ran = new java.util.Random(); for(int i = 0; i < count; i++){ int pos = ran.nextInt(base.length()); result += base.charAt(pos); } return result; } } }
実行結果
retNum[983] retAlpL[sdcdu] retNumAlp[cVTTIzhf] password[coso3OnOuL]