Java Random String generateRandomString(final String pattern)

Here you can find the source of generateRandomString(final String pattern)

Description

generate Random String

License

Open Source License

Declaration

public static String generateRandomString(final String pattern) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    private static final char[] LOWER_ALPHA_CHARS = ("abcdefghijklmnopqrstuvwxyz").toCharArray();
    private static final char[] UPPER_ALPHA_CHARS = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
    private static final char[] NUMERIC_CHARS = ("0123456789").toCharArray();
    private static final char[] SPECIAL_CHARS = ("!@#$%^&*()").toCharArray();
    private static final char[] ALL_CHARS = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
            .toCharArray();/*  ww w  .  j  a  va 2s  .c  o  m*/

    public static String generateRandomString(final String pattern) {

        if ((pattern == null) || (pattern.length() == 0)) {
            return "";
        }
        final char[] patternChars = pattern.toCharArray();
        final StringBuilder retVal = new StringBuilder(pattern.length());
        final java.util.Random rndGen = new java.util.Random();
        for (char patternChar : patternChars) {
            if (patternChar == '#') {
                retVal.append(NUMERIC_CHARS[rndGen.nextInt(NUMERIC_CHARS.length)]);
            } else if (patternChar == 'L') {
                retVal.append(LOWER_ALPHA_CHARS[rndGen.nextInt(LOWER_ALPHA_CHARS.length)]);
            } else if (patternChar == 'U') {
                retVal.append(UPPER_ALPHA_CHARS[rndGen.nextInt(UPPER_ALPHA_CHARS.length)]);
            } else if (patternChar == 'S') {
                retVal.append(SPECIAL_CHARS[rndGen.nextInt(SPECIAL_CHARS.length)]);
            } else if (patternChar == '*') {
                retVal.append(ALL_CHARS[rndGen.nextInt(ALL_CHARS.length)]);
            }
        }
        return retVal.toString();
    }
}

Related

  1. generateRandomString()
  2. generateRandomString()
  3. generateRandomString()
  4. generateRandomString()
  5. generateRandomString(final int minCharLen, final int maxCharLen)
  6. generateRandomString(int count)
  7. generateRandomString(int len)
  8. generateRandomString(int length)
  9. generateRandomString(int length)