在Python中生成匹配RegEx的字符串[duplicate]

时间:2022-09-13 16:28:25

Possible Duplicate:
Reversing a regular expression in python

可能的重复:在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.

我可以导入任何具有此功能的模块吗?最好不是使用re.search或re.match的蛮力方法。必须有一种更优雅的方式来做到这一点。

3 个解决方案

#1


19  

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

我一直在开发一个小助手库,用于用Python生成随机字符串

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

它包括一个方法,xeger(),它允许您从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


7  

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

exrex模块执行以下操作:https://github.com/asciimoo/exrex。

#3


1  

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.

因此,无法为给定的regex生成所有字符串。

#1


19  

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

我一直在开发一个小助手库,用于用Python生成随机字符串

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

它包括一个方法,xeger(),它允许您从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


7  

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

exrex模块执行以下操作:https://github.com/asciimoo/exrex。

#3


1  

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.

因此,无法为给定的regex生成所有字符串。