[SalesForce] How to generate a random string value based on regex pattern

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);
System.assert(myMatcher.matches());

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

Best Answer

  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].

Related Topic