是否有一个根据正则表达式生成数据的库? (Python或其他) [英] Is there a lib to generate data according to a regexp? (Python or other)
问题描述
考虑到正则表达式,我想生成随机数据x进行测试的时间。
Given a regexp, I would like to generate random data x number of time to test something.
例如
>>> 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.
是否存在类似的东西?如果可以,Python是否存在?如果没有,我可以使用任何线索/理论来做到这一点?
Does something like this exists? If it does, does it exists for Python? If not, any clue/theory I could use to do that?
推荐答案
Pyparsing包括此regex转换器,它返回简单正则表达式所有排列的生成器。以下是该模块中的一些测试用例:
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:
[A-C]{2}\d{2}
@|TH[12]
@(@|TH[12])?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
(([ECMP]|HA|AK)[SD]|HS)T
[A-CV]{2}
A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
(a|b)|(x|y)
编辑:
要进行随机选择,请创建一个排列列表(一次!),然后调用 random.choice
在列表中,每次您想要一个与正则表达式匹配的随机字符串时,都这样(未经测试):
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):
class RandomString(object):
def __init__(self, regex):
self.possible_strings = list(invRegex.invert(regex))
def random_string(self):
return random.choice(self.possible_strings)
这篇关于是否有一个根据正则表达式生成数据的库? (Python或其他)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!