是否有一个库可以根据正则表达式生成数据? (Python或其他)
给定一个正则表达式,我想生成随机数据 x 次来测试某些内容。
例如,
>>> print generate_date('\d{2,3}')
13
>>> print generate_date('\d{2,3}')
422
当然,目标是做一些比电话号码和电子邮件地址更复杂的事情。
这样的事情存在吗?如果存在,Python 是否存在?如果没有,我可以用什么线索/理论来做到这一点?
Given a regexp, I would like to generate random data x number of time to test something.
e.g.
>>> print generate_date('\d{2,3}')
13
>>> print generate_date('\d{2,3}')
422
Of course the objective is to do something a bit more complicated than that such as phone numbers and email addresses.
Does something like this exists? If it does, does it exists for Python? If not, any clue/theory I could use to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Pyparsing 包含这个正则表达式反相器,它返回所有的生成器简单正则表达式的排列。以下是该模块中的一些测试用例:
编辑:
要进行随机选择,请创建一个排列列表(一次!),然后调用
random.choice
每次您想要一个与正则表达式匹配的随机字符串时,都会在列表中,如下所示(未经测试):Pyparsing includes this regex inverter, which returns a generator of all permutations for simple regexes. Here are some of the test cases from that module:
Edit:
To do your random selection, create a list (once!) of your permutations, and then call
random.choice
on the list each time you want a random string that matches the regex, something like this (untested):Python 邮件列表上有一篇文章生成正则表达式所有排列的模块。我不太确定你会如何随机化它。我会继续检查。
There is a post on the Python mailing list about a module that generates all permutations of a regex. I'm not so sure how you might go about randomising it though. I'll keep checking.
我可能会因为提出这个建议而受到鞭打,但 Perl 有一个模块可以做到这一点。您可能想看看如何在 python 中实现它的代码:
http://p3rl.org/字符串::随机
I will probably be flogged for suggesting this, but perl has a module that does exactly this. You might want to take a look at the code how to implement it in python:
http://p3rl.org/String::Random