26

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

3 Answers 3

43

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No Python3 version?
Works in python3.8.1
15

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

6 Comments

+1 Works like a charm! It even install with easy_install :)
Alas, it's GPL; you can't use it in commercial software without contaminating it.
bitbucket.org/leapfrogdevelopment/rstr has a xeger method and is MIT
To clarify JDonner's comment for anyone finding this: it's AGPL; you can't even use it in server-side commercial software without releasing the source code to the entire executable that uses this library.
I guess it's not necessarily a bad thing, but it's very important that people understand the requirements of the license before using the library!
|
-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.

3 Comments

More to the point, any function you write to generate an arbitrary string could get stuck in an infinite loop at a*
asciimoo points to exrex which is implemented using generators. That way you can easily control the output and the size of it.
Not really. The requirement is to match a regex. "a" works, no need to generate all the possible scenarios.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.