RandomStringGenerator to generate alphanumeric strings

Viewed 12450

Can I use Apache's common-text RandomStringGenerator to generate random alphanumeric strings (numbers and lowercase/uppercase letters)?

5 Answers
RandomStringGenerator generator = new RandomStringGenerator.Builder()
    .selectFrom("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
    .build();

I kind of prefer this way rather than generating character codes and filtering out ones I don't want. And implicitly assuming that '0'..'z' includes all the codes I want, including capital letters (based on the ascii code chart).

In addition, depending on the application (eg password generation), you might want to use a CSPRNG (secure PRNG) seeded by a true-randomness source:

.usingRandom(new SecureRandom()::nextInt)

The default SecureRandom seed is from a true-randomness source of OS hardware device entropy.

The withinRange() method accepts min/max character pairs directly. So you can do:

char[][] allowedCharacterRanges = {{'a','z'},{'A','Z'},{'0','9'}};

RandomStringGenerator generator = new RandomStringGenerator.Builder()
    .withinRange( allowedCharacterRanges )
    .build();
Related