Samuel
Samuel

Reputation: 6247

How the regular expression search in opposite direction in python

For example. The string is following
"cd 1.2 ab 2.3 cd" .
If I use pattern "[0-9]*\.[0-9]*", and re.search to find the sub-string. It will return 1.2. I want to return 2.3.
How can I have the python search in opposite direction. I don't like to use findall function to get all of the sub-strings. then use the last one

Upvotes: 0

Views: 2938

Answers (4)

raton
raton

Reputation: 428

   1. re.search('[0-9]*\.[0-9]*',a[::-1]).group()


   2. re.search(r'(\d\.\d)(\s\w+$)',a).group(1)

Upvotes: 0

the wolf
the wolf

Reputation: 35532

If you want the last one (or last ones where you are willing to match a pattern) just use the greediest .* match up to the last pattern match of interest:

>>> import re
>>> st="cd 1.2 dv 1.4 ab 2.3 cd"
>>> re.match(r'.*(\d\.\d)',st).group(1)
'2.3'

But re.findall is more flexible and straightforward and probably the fastest:

>>> re.findall(r'(\d\.\d)',st)
['1.2', '1.4', '2.3']
>>> re.findall(r'(\d\.\d)',st)[-1]
'2.3'
>>> re.findall(r'(\d\.\d)',st)[-2]
'1.4'

Of course, you can reverse the string, match the FIRST match with a reversed regex (if it is not symmetrical), and reverse the result back:

>>> re.search(r'(\d\.\d)',st[::-1]).group(1)[::-1]
'2.3'

Which is done regularly in Perl

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

using re.finditer():

In [150]: strs="cd 1.2 ab 2.3 cd"

In [151]: for x in re.finditer(r"\d+\.\d+",strs):pass

In [152]: x.group()
Out[152]: '2.3'

Upvotes: 0

Firas Dib
Firas Dib

Reputation: 2621

This would work in this case: \d+\.\d+(?=\D*$)

It will grab the last digits when there are no others following it in the entire string.

Demo+explanation: http://regex101.com/r/hE0lE4

Upvotes: 7

Related Questions