Generate a String that matches a RegEx in Python [duplicate]

烈酒焚心 提交于 2019-12-18 02:27:39

问题


Possible Duplicate:
Reversing a regular expression in python

I think I ran into a problem that sounds easier than it is... I'm not too sure. I want to define a regular expression, and I want to build a number of strings matching it.

Is there any module I can import that has got this functionality? Preferably not a brute-force approach using re.search or re.match. There must be a more elegant way to do that.


回答1:


I've been working on a little helper library for generating random strings with Python

It includes a method, xeger() that allows you to create a string from a regex:

>>> import rstr
>>> rstr.xeger(r'[A-Z]\d[A-Z] \d[A-Z]\d')
u'M5R 2W4'

Right now, it works with most basic regular expressions.




回答2:


The exrex module does this: https://github.com/asciimoo/exrex.




回答3:


For some regular expressions, the list of possible strings can be infinite. For example:

a*

includes

a
aa
aaa

etc. Thus, there is no way to generate all strings for a given regex.



来源:https://stackoverflow.com/questions/4627464/generate-a-string-that-matches-a-regex-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!