随机生成器匹配正则表达式?

huangapple go评论92阅读模式
英文:

Random generator matching regexp?

问题

有没有一个Go包可以接收一个正则表达式作为输入,并返回一个匹配该正则表达式的随机字符串,或者你可以指导我如何实现这样的解决方案?

我的第一个想法是从/dev/rand中循环生成随机字节,然后返回一个与正则表达式匹配的字符串,但我认为这种暴力破解的方法会耗费很多时间,直到找到一个与正则表达式匹配的字符串。

用例:

我计划将其用于一个Web服务测试库。

  • 一些API调用,比如注册用户账户,需要唯一字段,比如电子邮件地址、电话号码等,因此需要基于模式/正则表达式的随机输入生成器。

  • 随机属性还有助于防止陈旧的数据/误报(即存储在当前测试套件之前的数据)。我猜生成器不需要提供密码级别的随机性,而是类似GUID的东西。

英文:

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.

答案1

得分: 5

Reggen 是我编写的一个库,可以根据正则表达式生成字符串。它可以用于生成所需的电子邮件地址/电话号码,以及使用正则表达式指定的其他内容。

一般来说,提供的正则表达式越具体,生成的结果越好。例如,正则表达式 .*@.*\..* 可能生成类似 F$-^@A"%mk.^uv 的字符串,但是 [a-z]+@[a-z]+\.(com|net|org) 应该生成类似 bfeujqp@qtpqby.com 的可读性更好的字符串。

使用该库生成电子邮件地址的示例代码:

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)
}

典型的输出结果:

tpbry@sfmxet.net
英文:

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 bfeujqp@qtpqby.com

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:

tpbry@sfmxet.net

huangapple
  • 本文由 发表于 2016年3月3日 03:46:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/35756696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定