Reputation: 10856
Is there any go package that receives a regex as input and returns a random string matching that regex or can you direct me how such a solution can be implemented?
My first thought is to generate random bytes in a loop from /dev/rand and then return one that matches the regex but I think this kind of brute-force would be time consuming until I find one such string matching the regex.
Use case:
I'm planning to use this for a web service testing library.
Some API calls such registering an user account requires unique fields such an email address, phone number etc thus the need of a random input generator based on a patter/regex.
The random property also helps to safeguard against stale data /false positives (i.e. data that was stored before the current test suite). I guess the generator doesn't need to provide cryptography level randomness but rather something like GUID.
Upvotes: 4
Views: 3593
Reputation: 141
Reggen is a library that I've written that can generate strings from regular expressions. It can be used to generate the email addresses/phone numbers you need, and anything else specified with a regular expression.
In general the more specific the provided regular expressions are, the better results it gives. For example, the regex .*@.*\..*
might generate something like F$-^@A"%mk.^uv
, but [a-z]+@[a-z]+\.(com|net|org)
should result in something more readable like [email protected]
Generating an email address with the library:
import "github.com/lucasjones/reggen"
func main() {
str, err := reggen.Generate("^[a-z]{5,10}@[a-z]{5,10}\\.(com|net|org)$", 10)
if err != nil {
panic(err)
}
fmt.Println(str)
}
Typical output:
[email protected]
Upvotes: 7