The user with no hat
The user with no hat

Reputation: 10856

Random generator matching regexp?

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.

Upvotes: 4

Views: 3593

Answers (1)

Lucas Jones
Lucas Jones

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

Related Questions