I am trying to create a method which will look at an Schema object and generate a value for that field which can be accepted. Here is one I am trying to match where the problem came around.
phoneNumber: {
type: String,
label: "Phone Number",
RegExp: /^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/
}
This will accept a string matching an American style phone numbers, e.g., (111)-111-1111
.
For a solution, I thought it'd be possible to recursively build a string and test it against the regex, returning if it matches, but that results in stack overflow (and isn't a great idea to begin with)
characters = frozenset([x for x in string.printable])
def generate_matching_string(re_str, regex):
" generates a string that matches a given regular expression "
if re.match(re_str, regex):
return re_str
letter = re_str[:-1]
if characters.index(letter) == len(characters):
re_str += characters[0]
else:
re_str[:-1] = characters[characters.index(letter) + 1]
return generate_matching_string(re_str, regex)
I imagine the first step would be something similar to a DFA.
Another concern: the result would have to at least be moderately random. That is to say, there should be some variation in results, adding another level of complexity.
How can one generate a string matching a regular expression programmatically? (language agnostic, conceptual is fine).