Pyparsing includes this regex inverter, which returns a generator of all permutations for simple regexes. Here are some of the test cases from that module:
[A-C]{2}\d{2}
@|TH[12]
@(@|TH[12])?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
(([ECMP]|HA|AK)[SD]|HS)T
[A-CV]{2}
A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
(a|b)|(x|y)
Edit:
To do your random selection, create a list (once!) of your permutations, and then call random.choice
on the list each time you want a random string that matches the regex, something like this (untested):
class RandomString(object):
def __init__(self, regex):
self.possible_strings = list(invRegex.invert(regex))
def random_string(self):
return random.choice(self.possible_strings)