Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a regular expression in Python

Tags:

python

regex

I want to reverse a regular expression. I.e. given a regular expression, I want to produce any string that will match that regex.

I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)

I'm using Python, so I'd like a Python library.

To reiterate, I only want one string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.

I'm willing for this library to only work on a certain subset of regex.

like image 992
Amandasaurus Avatar asked Jan 29 '09 18:01

Amandasaurus


People also ask

How do you reverse a regular expression?

Another way to show that reverse(L) is regular is via regular expressions. For any regular expression r you can construct a regular expression r such that L(r ) = reverse(L) using the inductive definition of regular languages.

How do you reverse an expression in Python?

The reversed() Built-in Function join() to create reversed strings. However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

Is it possible to reverse a string in regular expression?

reverse! # => "This string is backwards." s # => "This string is backwards." To reverse the order of the words in a string, split the string into a list of whitespaceseparated words, then join the list back into a string. The String#split method takes a regular expression to use as a separator.

What does re search return in Python?

re.search(): Finding pattern in text The re.search() function will search the regular expression pattern and return the first occurrence. Unlike Python re. match(), it will check all lines of the input string. If the pattern is found, the match object will be returned, otherwise “null” is returned.


1 Answers

Somebody else had a similar (duplicate?) question here, and I'd like to offer a little helper library for generating random strings with Python that I've been working on.

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, but I'm sure it could be improved.

like image 165
bjmc Avatar answered Sep 20 '22 05:09

bjmc