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
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.
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.
The ?! n quantifier matches any string that is not followed by a specific string n.
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.
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))):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With