last regular expression match

I am trying to find ways to do this other than these two:

# match last occurence of \d+, 24242 in this case
>>> test = "123_4242_24242lj.:"
>>> obj = re.search(r"\d+(?!.*\d)", test)
>>> obj.group()
'24242'
>>> re.findall(r"\d+", test)[-1]
'24242'
+3
source share
3 answers

This look-based regular expression matches the last digits in a string:

\d+(?=\D*$)
+1
source

I'm sure you can find smarter regexes that will do this, but I think you should stick with it findall().

Regular expressions are hard to read. Not only by others: let it be 10 days since you wrote one, and it will be difficult for you to read too. This makes their support difficult.

If performance is critical, it is always best to minimize the work performed by regular expressions. This line ...

re.findall(r"\d+", test)[-1]

... is clean, concise and immediately obvious.

+2

, :

. , , .

>>> import re
>>> test = "123_4242_24242lj.:"
>>> print re.findall(r'(\d+)\D*$', test)
['24242']
>>>

- :

>>> re.sub(r'.*?(\d+)\D*$', "\\1", test)
'24242'
+1
source

All Articles