goregen: github.com/zach-klippenstein/goregen Index | Examples | Files

package regen

import "github.com/zach-klippenstein/goregen"

Package regen is a library for generating random strings from regular expressions. The generated strings will match the expressions they were generated from. Similar to Ruby's randexp library.

E.g.

regen.Generate("[a-z0-9]{1,64}")

will return a lowercase alphanumeric string between 1 and 64 characters long.

Expressions are parsed using the Go standard library's parser: http://golang.org/pkg/regexp/syntax/.

Constraints

"." will generate any character, not necessarily a printable one.

"x{0,}", "x*", and "x+" will generate a random number of x's up to an arbitrary limit. If you care about the maximum number, specify it explicitly in the expression, e.g. "x{0,256}".

Flags

Flags can be passed to the parser by setting them in the GeneratorArgs struct. Newline flags are respected, and newlines won't be generated unless the appropriate flags for matching them are set.

E.g. Generate(".|[^a]") will never generate newlines. To generate newlines, create a generator and pass the flag syntax.MatchNL.

The Perl character class flag is supported, and required if the pattern contains them.

Unicode groups are not supported at this time. Support may be added in the future.

Concurrent Use

A generator can safely be used from multiple goroutines without locking.

A large bottleneck with running generators concurrently is actually the entropy source. Sources returned from rand.NewSource() are slow to seed, and not safe for concurrent use. Instead, the source passed in GeneratorArgs is used to seed an XorShift64 source (algorithm from the paper at http://vigna.di.unimi.it/ftp/papers/xorshift.pdf). This source only uses a single variable internally, and is much faster to seed than the default source. One source is created per call to NewGenerator. If no source is passed in, the default source is used to seed.

The source is not locked and does not use atomic operations, so there is a chance that multiple goroutines using the same source may get the same output. While obviously not cryptographically secure, I think the simplicity and performance benefit outweighs the risk of collisions. If you really care about preventing this, the solution is simple: don't call a single Generator from multiple goroutines.

Benchmarks

Benchmarks are included for creating and running generators for limited-length, complex regexes, and simple, highly-repetitive regexes.

go test -bench .

The complex benchmarks generate fake HTTP messages with the following regex:

POST (/[-a-zA-Z0-9_.]{3,12}){3,6}
Content-Length: [0-9]{2,3}
X-Auth-Token: [a-zA-Z0-9+/]{64}

([A-Za-z0-9+/]{64}
){3,15}[A-Za-z0-9+/]{60}([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)

The repetitive benchmarks use the regex

a{999}

See regen_benchmarks_test.go for more information.

On my mid-2014 MacBook Pro (2.6GHz Intel Core i5, 8GB 1600MHz DDR3), the results of running the benchmarks with minimal load are:

BenchmarkComplexCreation-4                       200	   8322160 ns/op
BenchmarkComplexGeneration-4                   10000	    153625 ns/op
BenchmarkLargeRepeatCreateSerial-4  	        3000	    411772 ns/op
BenchmarkLargeRepeatGenerateSerial-4	        5000	    291416 ns/op

Index

Examples

Package Files

char_class.go generator_error.go internal_generator.go regen.go regexp_format.go rng.go

Constants

const DefaultMaxUnboundedRepeatCount = 4096

DefaultMaxUnboundedRepeatCount is default value for MaxUnboundedRepeatCount.

func Generate Uses

func Generate(pattern string) (string, error)

Generate a random string that matches the regular expression pattern. If args is nil, default values are used.

This function does not seed the default RNG, so you must call rand.Seed() if you want non-deterministic strings.

Code:

pattern := "[ab]{5}"
str, _ := Generate(pattern)

if matched, _ := regexp.MatchString(pattern, str); matched {
    fmt.Println("Matches!")
}

Output:

Matches!

type CaptureGroupHandler Uses

type CaptureGroupHandler func(index int, name string, group *syntax.Regexp, generator Generator, args *GeneratorArgs) string

CaptureGroupHandler is a function that is called for each capture group in a regular expression. index and name are the index and name of the group. If unnamed, name is empty. The first capture group has index 0 (not 1, as when matching). group is the regular expression within the group (e.g. for `(\w+)`, group would be `\w+`). generator is the generator for group. args is the args used to create the generator calling this function.

Code:

pattern := `Hello, (?P<firstname>[A-Z][a-z]{2,10}) (?P<lastname>[A-Z][a-z]{2,10})`

generator, _ := NewGenerator(pattern, &GeneratorArgs{
    Flags: syntax.Perl,
    CaptureGroupHandler: func(index int, name string, group *syntax.Regexp, generator Generator, args *GeneratorArgs) string {
        if name == "firstname" {
            return fmt.Sprintf("FirstName (e.g. %s)", generator.Generate())
        }
        return fmt.Sprintf("LastName (e.g. %s)", generator.Generate())
    },
})

// Print to stderr since we're generating random output and can't assert equality.
fmt.Fprintln(os.Stderr, generator.Generate())

// Needed for "go test" to run this example. (Must be a blank line before.)

type Generator Uses

type Generator interface {
    Generate() string
    String() string
}

Generator generates random strings.

func NewGenerator Uses

func NewGenerator(pattern string, inputArgs *GeneratorArgs) (generator Generator, err error)

NewGenerator creates a generator that returns random strings that match the regular expression in pattern. If args is nil, default values are used.

Code:

pattern := "[ab]{5}"

// Note that this uses a constant seed, so the generated string
// will always be the same across different runs of the program.
// Use a more random seed for real use (e.g. time-based).
generator, _ := NewGenerator(pattern, &GeneratorArgs{
    RngSource: rand.NewSource(0),
})

str := generator.Generate()

if matched, _ := regexp.MatchString(pattern, str); matched {
    fmt.Println("Matches!")
}

Output:

Matches!

Code:

pattern := `\d{5}`

generator, _ := NewGenerator(pattern, &GeneratorArgs{
    Flags: syntax.Perl,
})

str := generator.Generate()

if matched, _ := regexp.MatchString("[[:digit:]]{5}", str); matched {
    fmt.Println("Matches!")
}

Output:

Matches!

type GeneratorArgs Uses

type GeneratorArgs struct {
    // May be nil.
    // Used to seed a custom RNG that is a lot faster than the default implementation.
    // See http://vigna.di.unimi.it/ftp/papers/xorshift.pdf.
    RngSource rand.Source

    // Default is 0 (syntax.POSIX).
    Flags syntax.Flags

    // Maximum number of instances to generate for unbounded repeat expressions (e.g. ".*" and "{1,}")
    // Default is DefaultMaxUnboundedRepeatCount.
    MaxUnboundedRepeatCount uint
    // Minimum number of instances to generate for unbounded repeat expressions (e.g. ".*")
    // Default is 0.
    MinUnboundedRepeatCount uint

    // Set this to perform special processing of capture groups (e.g. `(\w+)`). The zero value will generate strings
    // from the expressions in the group.
    CaptureGroupHandler CaptureGroupHandler
    // contains filtered or unexported fields
}

GeneratorArgs are arguments passed to NewGenerator that control how generators are created.

func (*GeneratorArgs) Rng Uses

func (a *GeneratorArgs) Rng() *rand.Rand

Rng returns the random number generator used by generators. Panics if called before the GeneratorArgs has been initialized by NewGenerator.

Package regen imports 6 packages (graph) and is imported by 36 packages. Updated 2016-07-25. Refresh now. Tools for package owners.