在 Python 中生成与 RegEx 匹配的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4627464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:35:49  来源:igfitidea点击:

Generate a String that matches a RegEx in Python

pythonregexstringbuilder

提问by wishi

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.searchor re.match. There must be a more elegant way to do that.

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

采纳答案by bjmc

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()允许您从正则表达式创建字符串:

>>> 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.

现在,它适用于大多数基本的正则表达式。

回答by chrisaycock

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.

因此,无法为给定的正则表达式生成所有字符串。

回答by asciimoo

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

exrex 模块执行此操作:https: //github.com/asciimoo/exrex