Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reverse a regex in python?

My regex is something like below

    text = 'id 5 result pass
            id 4 result fail
            id 3 result fail
            id 2 result fail
            id 1 result pass'

    for i in re.finditer('id (.+?) result (.+)', text): 
         id = i.group(1)
         result = i.group(2)
         print 'id' 
         print 'result' 

The output is OK. But how do I reverse it to get the results in the other order where id will start from 1 with the pass or fail result

like image 568
Abul Hasnat Avatar asked Jul 08 '13 02:07

Abul Hasnat


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 Functionjoin() 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.

What is ?! In RegEx?

The ?! n quantifier matches any string that is not followed by a specific string n.

Does Python replace take RegEx?

To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.


1 Answers

A good way is (which will be faster than using a lambda in the sorted):

sorted(re.finditer(...,text),key=attrgetter('group'),reverse=True):

Or you could turn the iterator into a list and reverse it:

for i in reversed(list(re.finditer('id (.+?) result (.+)', text))): 
like image 136
HennyH Avatar answered Sep 16 '22 22:09

HennyH