简体   繁体   English

Python-从正则表达式生成指定长度的随机字符串

[英]Python - generating random string of specified length from regular expression

My string length is allowed not more than 255 characters. 我的字符串长度不能超过255个字符。 The following Regular expression can be taken for example- 下列正则表达式可以举个例子-

^([a-zA-Z0-9]{1}((-|[a-zA-Z0-9])*[a-zA-Z0-9])*[.])*[a-zA-Z]{1}((-|[a-zA-Z0-9])*[a-zA-Z0-9])*\.?$

i am using exrex.getone(regular_expression) function for generating strings where i can't control generated string length. 我正在使用exrex.getone(regular_expression)函数生成无法控制生成的字符串长度的字符串。
How to generate a string of intended length which satisfy the Regular Expression also ? 如何生成预期长度的字符串,该字符串也要满足正则表达式?
Till now i have not seen any answer satisfying this condition. 到目前为止,我还没有任何满足此条件的答案。

From exrex website: exrex网站:

There are regular expressions with infinite matching strings (eg.: [az]+ ), in these cases exrex limits the maximum length of the infinite parts. 有带有无限匹配字符串的正则表达式(例如:[az] +),在这些情况下,exrex限制了无限部分的最大长度。

and the code itself: 和代码本身:

418 def getone(regex_string, limit=20): 
419     """Returns a random matching string to a given regular expression 
420     """ 
421     return _randone(parse(regex_string), limit) 

So there's a limit keyword. 因此,有一个limit关键字。 I couldn't tell for sure if this limits the entire string or each infinite part, but I think it's the latter. 我不确定这是否限制整个字符串或每个无限部分,但我认为是后者。 Try limiting this to something smaller, like 4. 尝试将其限制为较小的值,例如4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM