Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 553
wishi Avatar asked Jan 07 '11 16:01

wishi


People also ask

How do you create a string in regex?

Just enter your regexp in the field below, press the Generate Text button, and you'll get a random text that matches your regexp. Press a button – invert a regexp. No ads, nonsense, or garbage.

How do you split a string by the occurrences of a regex pattern in Python?

If you want to split a string that matches a regular expression (regex) instead of perfect match, use the split() of the re module. In re. split() , specify the regex pattern in the first parameter and the target character string in the second parameter. An example of split by consecutive numbers is as follows.

Does re match return a string?

Both return the first match of a substring found in the string, but re. match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none.


3 Answers

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.

like image 118
bjmc Avatar answered Sep 21 '22 06:09

bjmc


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

like image 42
asciimoo Avatar answered Sep 23 '22 06:09

asciimoo


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.

like image 43
chrisaycock Avatar answered Sep 21 '22 06:09

chrisaycock