I'm trying to build a random external ID generator that can take a complex pattern described in RegEx and generate any number of unique strings for unit tests.

Ideally something like Xeger which makes it really simple.

I'm considering a lengthy process of indexing separators, removing them, randomizing a string and restoring separators but that's not as portable across ID formats. Any suggestions for creative solutions?

This would be useful in unit tests for following patterns like Social Security Numbers or Phone Numbers, as well as in code directly for creating new IDs.

Example for Social Security Numbers:

String regex = '[0-9]{3}-[0-9]{2}-[0-9]{4}';
String myId = String.generateRandom(regex);

Pattern myPattern = Pattern.compile(regex);
Matcher myMatcher = MyPattern.matcher(myId);

I also submitted an idea to the IdeaExchange for this, so if you think it's worthy, please vote!

2 Answers 2

  1. You need a class, which can create a random string of a specific length for a given alphabet. This can be achieved by using Crypto.getRandomInteger() and mapping it to a character of the alphabet
  2. Then you need a class, which parses the regex and creates an alphabet and length for each bracket expression and its following count [a-z]{2}. The alphabet creation would be the hardest part.
  3. Then you can feed your random string class and replace each bracket expression with its results.
  4. You could even match the pattern against the result to check, if it has been replaced correctly.

Glancing over the Xeger limitations, it seems to be a good idea to define a base alphabet like List<String> ALPHANUMERIC = new List<String> {'A', 'B', 'C', 'D', 'E', 'F', 'G'...}; to support things like .* or [^a-z].


For something like socials and feins, they also need to be somewhat unique, so I've always just kludged some Math.random methods together to make a generateFeinList or generateSsnList to give me a list of N numbers that are unique within the set. You could also use String.fromCharArray to get the same thing... I just hope randomly generated data for tests doesn't inconsistently give you deploy failures! :-D

  • 1
    fein = Federal Employer Identification Number for the non-Americans on the community
    – cropredy
    Commented Oct 28, 2014 at 17:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .